blob: f232d61f7a8f9ff3d6f17d3364d1d5970bbf3500 [file] [log] [blame]
Misha Brukmanebb0faa2004-06-18 15:38:49 +00001//===- SystemUtils.cpp - Utilities for low-level system tasks -------------===//
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/fcntl.h"
Misha Brukmanb4873032004-06-18 15:34:07 +000018#include "Config/pagesize.h"
John Criswell7a73b802003-06-30 21:59:07 +000019#include "Config/unistd.h"
Misha Brukmanebb0faa2004-06-18 15:38:49 +000020#include "Config/windows.h"
21#include "Config/sys/mman.h"
22#include "Config/sys/stat.h"
23#include "Config/sys/types.h"
24#include "Config/sys/wait.h"
Chris Lattner74b1f452004-01-10 19:15:14 +000025#include <algorithm>
Misha Brukmanebb0faa2004-06-18 15:38:49 +000026#include <cerrno>
27#include <cstdlib>
Chris Lattner74b1f452004-01-10 19:15:14 +000028#include <fstream>
29#include <iostream>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattner4a106452002-12-23 23:50:16 +000032/// isExecutableFile - This function returns true if the filename specified
33/// exists and is executable.
34///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000035bool llvm::isExecutableFile(const std::string &ExeFileName) {
Chris Lattner4a106452002-12-23 23:50:16 +000036 struct stat Buf;
37 if (stat(ExeFileName.c_str(), &Buf))
38 return false; // Must not be executable!
39
40 if (!(Buf.st_mode & S_IFREG))
41 return false; // Not a regular file?
42
43 if (Buf.st_uid == getuid()) // Owner of file?
44 return Buf.st_mode & S_IXUSR;
45 else if (Buf.st_gid == getgid()) // In group of file?
46 return Buf.st_mode & S_IXGRP;
47 else // Unrelated to file?
48 return Buf.st_mode & S_IXOTH;
49}
50
Chris Lattnerb234d462004-04-02 05:04:03 +000051/// isStandardOutAConsole - Return true if we can tell that the standard output
52/// stream goes to a terminal window or console.
53bool llvm::isStandardOutAConsole() {
Brian Gaeke8507ecb2004-04-02 21:26:04 +000054#if HAVE_ISATTY
Chris Lattnerb234d462004-04-02 05:04:03 +000055 return isatty(1);
Brian Gaeke8507ecb2004-04-02 21:26:04 +000056#endif
57 // If we don't have isatty, just return false.
58 return false;
Chris Lattnerb234d462004-04-02 05:04:03 +000059}
60
61
Misha Brukmanf7066c72003-08-07 21:34:25 +000062/// FindExecutable - Find a named executable, giving the argv[0] of program
Misha Brukman44f8a342003-09-29 22:40:07 +000063/// being executed. This allows us to find another LLVM tool if it is built
64/// into the same directory, but that directory is neither the current
65/// directory, nor in the PATH. If the executable cannot be found, return an
66/// empty string.
Misha Brukmanf7066c72003-08-07 21:34:25 +000067///
Chris Lattner49f61c42004-05-28 01:20:58 +000068#undef FindExecutable // needed on windows :(
Chris Lattner2cdd21c2003-12-14 21:35:53 +000069std::string llvm::FindExecutable(const std::string &ExeName,
70 const std::string &ProgramPath) {
Chris Lattner4a106452002-12-23 23:50:16 +000071 // First check the directory that bugpoint is in. We can do this if
72 // BugPointPath contains at least one / character, indicating that it is a
73 // relative path to bugpoint itself.
74 //
Misha Brukman35d402f2003-08-07 21:33:33 +000075 std::string Result = ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +000076 while (!Result.empty() && Result[Result.size()-1] != '/')
77 Result.erase(Result.size()-1, 1);
78
79 if (!Result.empty()) {
80 Result += ExeName;
81 if (isExecutableFile(Result)) return Result; // Found it?
82 }
83
Misha Brukman35d402f2003-08-07 21:33:33 +000084 // Okay, if the path to the program didn't tell us anything, try using the
85 // PATH environment variable.
Chris Lattner4a106452002-12-23 23:50:16 +000086 const char *PathStr = getenv("PATH");
87 if (PathStr == 0) return "";
88
Misha Brukmanbc0e9982003-07-14 17:20:40 +000089 // Now we have a colon separated list of directories to search... try them...
Chris Lattner4a106452002-12-23 23:50:16 +000090 unsigned PathLen = strlen(PathStr);
91 while (PathLen) {
92 // Find the first colon...
93 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
94
95 // Check to see if this first directory contains the executable...
96 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
97 if (isExecutableFile(FilePath))
98 return FilePath; // Found the executable!
99
100 // Nope it wasn't in this directory, check the next range!
101 PathLen -= Colon-PathStr;
102 PathStr = Colon;
103 while (*PathStr == ':') { // Advance past colons
104 PathStr++;
105 PathLen--;
106 }
107 }
108
109 // If we fell out, we ran out of directories in PATH to search, return failure
110 return "";
111}
112
113static void RedirectFD(const std::string &File, int FD) {
114 if (File.empty()) return; // Noop
115
116 // Open the file
117 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
118 if (InFD == -1) {
119 std::cerr << "Error opening file '" << File << "' for "
Misha Brukman44f8a342003-09-29 22:40:07 +0000120 << (FD == 0 ? "input" : "output") << "!\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000121 exit(1);
122 }
123
124 dup2(InFD, FD); // Install it as the requested FD
125 close(InFD); // Close the original FD
126}
127
Chris Lattnerde0213b2004-07-24 07:41:31 +0000128static bool Timeout = false;
129static void TimeOutHandler(int Sig) {
130 Timeout = true;
131}
132
Chris Lattner4a106452002-12-23 23:50:16 +0000133/// RunProgramWithTimeout - This function executes the specified program, with
134/// the specified null-terminated argument array, with the stdin/out/err fd's
Chris Lattnerde0213b2004-07-24 07:41:31 +0000135/// redirected, with a timeout specified by the last argument. This terminates
Chris Lattner4a106452002-12-23 23:50:16 +0000136/// the calling program if there is an error executing the specified program.
137/// It returns the return value of the program, or -1 if a timeout is detected.
138///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000139int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
140 const char **Args,
141 const std::string &StdInFile,
142 const std::string &StdOutFile,
Chris Lattnerde0213b2004-07-24 07:41:31 +0000143 const std::string &StdErrFile,
144 unsigned NumSeconds) {
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000145#ifdef HAVE_SYS_WAIT_H
Chris Lattner4a106452002-12-23 23:50:16 +0000146 int Child = fork();
147 switch (Child) {
148 case -1:
149 std::cerr << "ERROR forking!\n";
150 exit(1);
151 case 0: // Child
152 RedirectFD(StdInFile, 0); // Redirect file descriptors...
153 RedirectFD(StdOutFile, 1);
Chris Lattnerbf3d2e22004-04-16 05:35:58 +0000154 if (StdOutFile != StdErrFile)
155 RedirectFD(StdErrFile, 2);
156 else
157 dup2(1, 2);
Chris Lattner4a106452002-12-23 23:50:16 +0000158
159 execv(ProgramPath.c_str(), (char *const *)Args);
Brian Gaeke53e557d2003-10-15 20:46:58 +0000160 std::cerr << "Error executing program: '" << ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +0000161 for (; *Args; ++Args)
162 std::cerr << " " << *Args;
Brian Gaeke53e557d2003-10-15 20:46:58 +0000163 std::cerr << "'\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000164 exit(1);
165
166 default: break;
167 }
168
169 // Make sure all output has been written while waiting
170 std::cout << std::flush;
171
Chris Lattnerde0213b2004-07-24 07:41:31 +0000172 // Install a timeout handler.
173 Timeout = false;
174 struct sigaction Act, Old;
175 Act.sa_sigaction = 0;
176 Act.sa_handler = TimeOutHandler;
177 Act.sa_flags = SA_NOMASK;
178 sigaction(SIGALRM, &Act, &Old);
179
180 // Set the timeout if one is set.
181 if (NumSeconds)
182 alarm(NumSeconds);
183
Chris Lattner4a106452002-12-23 23:50:16 +0000184 int Status;
Chris Lattnerde0213b2004-07-24 07:41:31 +0000185 while (wait(&Status) != Child) {
Chris Lattner4a106452002-12-23 23:50:16 +0000186 if (errno == EINTR) {
Chris Lattnerde0213b2004-07-24 07:41:31 +0000187 if (Timeout) {
188 static bool FirstTimeout = true;
189 if (FirstTimeout) {
190 std::cout <<
Chris Lattner4a106452002-12-23 23:50:16 +0000191 "*** Program execution timed out! This mechanism is designed to handle\n"
192 " programs stuck in infinite loops gracefully. The -timeout option\n"
193 " can be used to change the timeout threshold or disable it completely\n"
194 " (with -timeout=0). This message is only displayed once.\n";
Chris Lattnerde0213b2004-07-24 07:41:31 +0000195 FirstTimeout = false;
196 }
Chris Lattner4a106452002-12-23 23:50:16 +0000197 }
Chris Lattner4a106452002-12-23 23:50:16 +0000198
Chris Lattnerde0213b2004-07-24 07:41:31 +0000199 // Kill the child.
200 kill(Child, SIGKILL);
201
202 if (wait(&Status) != Child)
203 std::cerr << "Something funny happened waiting for the child!\n";
204
205 alarm(0);
206 sigaction(SIGALRM, &Old, 0);
207 return -1; // Timeout detected
208 } else {
209 std::cerr << "Error waiting for child process!\n";
210 exit(1);
211 }
Chris Lattner4a106452002-12-23 23:50:16 +0000212 }
Chris Lattnerde0213b2004-07-24 07:41:31 +0000213
214 alarm(0);
215 sigaction(SIGALRM, &Old, 0);
Chris Lattner4a106452002-12-23 23:50:16 +0000216 return Status;
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000217
218#else
219 std::cerr << "RunProgramWithTimeout not implemented on this platform!\n";
220 return -1;
221#endif
Chris Lattner4a106452002-12-23 23:50:16 +0000222}
John Criswell5afb5f62003-09-17 15:13:59 +0000223
224
Misha Brukmand6af6862004-06-02 00:09:46 +0000225// ExecWait - executes a program with the specified arguments and environment.
226// It then waits for the progarm to termiante and then returns to the caller.
John Criswell5afb5f62003-09-17 15:13:59 +0000227//
228// Inputs:
229// argv - The arguments to the program as an array of C strings. The first
230// argument should be the name of the program to execute, and the
231// last argument should be a pointer to NULL.
232//
233// envp - The environment passes to the program as an array of C strings in
234// the form of "name=value" pairs. The last element should be a
235// pointer to NULL.
236//
237// Outputs:
238// None.
239//
240// Return value:
241// 0 - No errors.
242// 1 - The program could not be executed.
243// 1 - The program returned a non-zero exit status.
244// 1 - The program terminated abnormally.
245//
246// Notes:
247// The program will inherit the stdin, stdout, and stderr file descriptors
248// as well as other various configuration settings (umask).
249//
250// This function should not print anything to stdout/stderr on its own. It is
251// a generic library function. The caller or executed program should report
252// errors in the way it sees fit.
253//
John Criswelle5b3e152003-09-17 19:02:49 +0000254// This function does not use $PATH to find programs.
255//
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000256int llvm::ExecWait(const char * const old_argv[],
257 const char * const old_envp[]) {
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000258#ifdef HAVE_SYS_WAIT_H
John Criswelle5b3e152003-09-17 19:02:49 +0000259 // Create local versions of the parameters that can be passed into execve()
260 // without creating const problems.
John Criswelle5b3e152003-09-17 19:02:49 +0000261 char ** const argv = (char ** const) old_argv;
262 char ** const envp = (char ** const) old_envp;
John Criswell5afb5f62003-09-17 15:13:59 +0000263
John Criswell5afb5f62003-09-17 15:13:59 +0000264 // Create a child process.
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000265 switch (fork()) {
John Criswelle5b3e152003-09-17 19:02:49 +0000266 // An error occured: Return to the caller.
John Criswell5afb5f62003-09-17 15:13:59 +0000267 case -1:
268 return 1;
269 break;
270
John Criswelle5b3e152003-09-17 19:02:49 +0000271 // Child process: Execute the program.
John Criswell5afb5f62003-09-17 15:13:59 +0000272 case 0:
John Criswelle5b3e152003-09-17 19:02:49 +0000273 execve (argv[0], argv, envp);
John Criswelle5b3e152003-09-17 19:02:49 +0000274 // If the execve() failed, we should exit and let the parent pick up
275 // our non-zero exit status.
John Criswelle5b3e152003-09-17 19:02:49 +0000276 exit (1);
John Criswell5afb5f62003-09-17 15:13:59 +0000277
John Criswelle5b3e152003-09-17 19:02:49 +0000278 // Parent process: Break out of the switch to do our processing.
John Criswell5afb5f62003-09-17 15:13:59 +0000279 default:
280 break;
281 }
282
Misha Brukmand6af6862004-06-02 00:09:46 +0000283 // Parent process: Wait for the child process to terminate.
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000284 int status;
John Criswell5afb5f62003-09-17 15:13:59 +0000285 if ((wait (&status)) == -1)
John Criswell5afb5f62003-09-17 15:13:59 +0000286 return 1;
John Criswell5afb5f62003-09-17 15:13:59 +0000287
John Criswell5afb5f62003-09-17 15:13:59 +0000288 // If the program exited normally with a zero exit status, return success!
John Criswell5afb5f62003-09-17 15:13:59 +0000289 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
John Criswell5afb5f62003-09-17 15:13:59 +0000290 return 0;
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000291#else
292 std::cerr << "llvm::ExecWait not implemented on this platform!\n";
293#endif
John Criswell5afb5f62003-09-17 15:13:59 +0000294
John Criswell5afb5f62003-09-17 15:13:59 +0000295 // Otherwise, return failure.
John Criswell5afb5f62003-09-17 15:13:59 +0000296 return 1;
297}
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000298
299/// AllocateRWXMemory - Allocate a slab of memory with read/write/execute
300/// permissions. This is typically used for JIT applications where we want
301/// to emit code to the memory then jump to it. Getting this type of memory
302/// is very OS specific.
303///
304void *llvm::AllocateRWXMemory(unsigned NumBytes) {
305 if (NumBytes == 0) return 0;
Chris Lattner49f61c42004-05-28 01:20:58 +0000306
307#if defined(HAVE_WINDOWS_H)
308 // On windows we use VirtualAlloc.
309 void *P = VirtualAlloc(0, NumBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
310 if (P == 0) {
311 std::cerr << "Error allocating executable memory!\n";
312 abort();
313 }
314 return P;
315
316#elif defined(HAVE_MMAP)
Misha Brukmanb4873032004-06-18 15:34:07 +0000317 static const long pageSize = GetPageSize();
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000318 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
319
320/* FIXME: This should use the proper autoconf flags */
321#if defined(i386) || defined(__i386__) || defined(__x86__)
322 /* Linux and *BSD tend to have these flags named differently. */
323#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
324# define MAP_ANONYMOUS MAP_ANON
325#endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
326#elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
327/* nothing */
328#else
Chris Lattner49f61c42004-05-28 01:20:58 +0000329 std::cerr << "This architecture has an unknown MMAP implementation!\n";
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000330 abort();
331 return 0;
332#endif
333
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000334 int fd = -1;
335#if defined(__linux__)
336 fd = 0;
337#endif
338
339 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
340#ifdef MAP_NORESERVE
341 mmapFlags |= MAP_NORESERVE;
342#endif
343
344 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
345 mmapFlags, fd, 0);
346 if (pa == MAP_FAILED) {
347 perror("mmap");
348 abort();
349 }
350 return pa;
351#else
352 std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";
353 abort();
354 return 0;
355#endif
356}
357
358