blob: b831f4096d0f4facbc7b73c1902e333b0433c5e7 [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 Lattnerd67e4392004-07-25 07:34:00 +000030#include <signal.h>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattner4a106452002-12-23 23:50:16 +000033/// isExecutableFile - This function returns true if the filename specified
34/// exists and is executable.
35///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000036bool llvm::isExecutableFile(const std::string &ExeFileName) {
Chris Lattner4a106452002-12-23 23:50:16 +000037 struct stat Buf;
38 if (stat(ExeFileName.c_str(), &Buf))
39 return false; // Must not be executable!
40
41 if (!(Buf.st_mode & S_IFREG))
42 return false; // Not a regular file?
43
44 if (Buf.st_uid == getuid()) // Owner of file?
45 return Buf.st_mode & S_IXUSR;
46 else if (Buf.st_gid == getgid()) // In group of file?
47 return Buf.st_mode & S_IXGRP;
48 else // Unrelated to file?
49 return Buf.st_mode & S_IXOTH;
50}
51
Chris Lattnerb234d462004-04-02 05:04:03 +000052/// isStandardOutAConsole - Return true if we can tell that the standard output
53/// stream goes to a terminal window or console.
54bool llvm::isStandardOutAConsole() {
Brian Gaeke8507ecb2004-04-02 21:26:04 +000055#if HAVE_ISATTY
Chris Lattnerb234d462004-04-02 05:04:03 +000056 return isatty(1);
Brian Gaeke8507ecb2004-04-02 21:26:04 +000057#endif
58 // If we don't have isatty, just return false.
59 return false;
Chris Lattnerb234d462004-04-02 05:04:03 +000060}
61
62
Misha Brukmanf7066c72003-08-07 21:34:25 +000063/// FindExecutable - Find a named executable, giving the argv[0] of program
Misha Brukman44f8a342003-09-29 22:40:07 +000064/// being executed. This allows us to find another LLVM tool if it is built
65/// into the same directory, but that directory is neither the current
66/// directory, nor in the PATH. If the executable cannot be found, return an
67/// empty string.
Misha Brukmanf7066c72003-08-07 21:34:25 +000068///
Chris Lattner49f61c42004-05-28 01:20:58 +000069#undef FindExecutable // needed on windows :(
Chris Lattner2cdd21c2003-12-14 21:35:53 +000070std::string llvm::FindExecutable(const std::string &ExeName,
71 const std::string &ProgramPath) {
Chris Lattner4a106452002-12-23 23:50:16 +000072 // First check the directory that bugpoint is in. We can do this if
73 // BugPointPath contains at least one / character, indicating that it is a
74 // relative path to bugpoint itself.
75 //
Misha Brukman35d402f2003-08-07 21:33:33 +000076 std::string Result = ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +000077 while (!Result.empty() && Result[Result.size()-1] != '/')
78 Result.erase(Result.size()-1, 1);
79
80 if (!Result.empty()) {
81 Result += ExeName;
82 if (isExecutableFile(Result)) return Result; // Found it?
83 }
84
Misha Brukman35d402f2003-08-07 21:33:33 +000085 // Okay, if the path to the program didn't tell us anything, try using the
86 // PATH environment variable.
Chris Lattner4a106452002-12-23 23:50:16 +000087 const char *PathStr = getenv("PATH");
88 if (PathStr == 0) return "";
89
Misha Brukmanbc0e9982003-07-14 17:20:40 +000090 // Now we have a colon separated list of directories to search... try them...
Chris Lattner4a106452002-12-23 23:50:16 +000091 unsigned PathLen = strlen(PathStr);
92 while (PathLen) {
93 // Find the first colon...
94 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
95
96 // Check to see if this first directory contains the executable...
97 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
98 if (isExecutableFile(FilePath))
99 return FilePath; // Found the executable!
100
101 // Nope it wasn't in this directory, check the next range!
102 PathLen -= Colon-PathStr;
103 PathStr = Colon;
104 while (*PathStr == ':') { // Advance past colons
105 PathStr++;
106 PathLen--;
107 }
108 }
109
110 // If we fell out, we ran out of directories in PATH to search, return failure
111 return "";
112}
113
114static void RedirectFD(const std::string &File, int FD) {
115 if (File.empty()) return; // Noop
116
117 // Open the file
118 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
119 if (InFD == -1) {
120 std::cerr << "Error opening file '" << File << "' for "
Misha Brukman44f8a342003-09-29 22:40:07 +0000121 << (FD == 0 ? "input" : "output") << "!\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000122 exit(1);
123 }
124
125 dup2(InFD, FD); // Install it as the requested FD
126 close(InFD); // Close the original FD
127}
128
Chris Lattnerde0213b2004-07-24 07:41:31 +0000129static bool Timeout = false;
130static void TimeOutHandler(int Sig) {
131 Timeout = true;
132}
133
Chris Lattner4a106452002-12-23 23:50:16 +0000134/// RunProgramWithTimeout - This function executes the specified program, with
135/// the specified null-terminated argument array, with the stdin/out/err fd's
Chris Lattnerde0213b2004-07-24 07:41:31 +0000136/// redirected, with a timeout specified by the last argument. This terminates
Chris Lattner4a106452002-12-23 23:50:16 +0000137/// the calling program if there is an error executing the specified program.
138/// It returns the return value of the program, or -1 if a timeout is detected.
139///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000140int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
141 const char **Args,
142 const std::string &StdInFile,
143 const std::string &StdOutFile,
Chris Lattnerde0213b2004-07-24 07:41:31 +0000144 const std::string &StdErrFile,
145 unsigned NumSeconds) {
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000146#ifdef HAVE_SYS_WAIT_H
Chris Lattner4a106452002-12-23 23:50:16 +0000147 int Child = fork();
148 switch (Child) {
149 case -1:
150 std::cerr << "ERROR forking!\n";
151 exit(1);
152 case 0: // Child
153 RedirectFD(StdInFile, 0); // Redirect file descriptors...
154 RedirectFD(StdOutFile, 1);
Chris Lattnerbf3d2e22004-04-16 05:35:58 +0000155 if (StdOutFile != StdErrFile)
156 RedirectFD(StdErrFile, 2);
157 else
158 dup2(1, 2);
Chris Lattner4a106452002-12-23 23:50:16 +0000159
160 execv(ProgramPath.c_str(), (char *const *)Args);
Brian Gaeke53e557d2003-10-15 20:46:58 +0000161 std::cerr << "Error executing program: '" << ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +0000162 for (; *Args; ++Args)
163 std::cerr << " " << *Args;
Brian Gaeke53e557d2003-10-15 20:46:58 +0000164 std::cerr << "'\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000165 exit(1);
166
167 default: break;
168 }
169
170 // Make sure all output has been written while waiting
171 std::cout << std::flush;
172
Chris Lattnerde0213b2004-07-24 07:41:31 +0000173 // Install a timeout handler.
174 Timeout = false;
175 struct sigaction Act, Old;
176 Act.sa_sigaction = 0;
177 Act.sa_handler = TimeOutHandler;
Chris Lattnerd67e4392004-07-25 07:34:00 +0000178 sigemptyset(&Act.sa_mask);
179 Act.sa_flags = 0;
Chris Lattnerde0213b2004-07-24 07:41:31 +0000180 sigaction(SIGALRM, &Act, &Old);
181
182 // Set the timeout if one is set.
183 if (NumSeconds)
184 alarm(NumSeconds);
185
Chris Lattner4a106452002-12-23 23:50:16 +0000186 int Status;
Chris Lattner21ddf172004-07-24 07:50:48 +0000187 while (wait(&Status) != Child)
Chris Lattner4a106452002-12-23 23:50:16 +0000188 if (errno == EINTR) {
Chris Lattnerde0213b2004-07-24 07:41:31 +0000189 if (Timeout) {
Chris Lattner21ddf172004-07-24 07:50:48 +0000190 // Kill the child.
191 kill(Child, SIGKILL);
192
193 if (wait(&Status) != Child)
194 std::cerr << "Something funny happened waiting for the child!\n";
195
196 alarm(0);
197 sigaction(SIGALRM, &Old, 0);
198 return -1; // Timeout detected
199 } else {
200 std::cerr << "Error waiting for child process!\n";
201 exit(1);
Chris Lattner4a106452002-12-23 23:50:16 +0000202 }
Chris Lattnerde0213b2004-07-24 07:41:31 +0000203 }
Chris Lattnerde0213b2004-07-24 07:41:31 +0000204
205 alarm(0);
206 sigaction(SIGALRM, &Old, 0);
Chris Lattner4a106452002-12-23 23:50:16 +0000207 return Status;
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000208
209#else
210 std::cerr << "RunProgramWithTimeout not implemented on this platform!\n";
211 return -1;
212#endif
Chris Lattner4a106452002-12-23 23:50:16 +0000213}
John Criswell5afb5f62003-09-17 15:13:59 +0000214
215
Misha Brukmand6af6862004-06-02 00:09:46 +0000216// ExecWait - executes a program with the specified arguments and environment.
217// It then waits for the progarm to termiante and then returns to the caller.
John Criswell5afb5f62003-09-17 15:13:59 +0000218//
219// Inputs:
220// argv - The arguments to the program as an array of C strings. The first
221// argument should be the name of the program to execute, and the
222// last argument should be a pointer to NULL.
223//
224// envp - The environment passes to the program as an array of C strings in
225// the form of "name=value" pairs. The last element should be a
226// pointer to NULL.
227//
228// Outputs:
229// None.
230//
231// Return value:
232// 0 - No errors.
233// 1 - The program could not be executed.
234// 1 - The program returned a non-zero exit status.
235// 1 - The program terminated abnormally.
236//
237// Notes:
238// The program will inherit the stdin, stdout, and stderr file descriptors
239// as well as other various configuration settings (umask).
240//
241// This function should not print anything to stdout/stderr on its own. It is
242// a generic library function. The caller or executed program should report
243// errors in the way it sees fit.
244//
John Criswelle5b3e152003-09-17 19:02:49 +0000245// This function does not use $PATH to find programs.
246//
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000247int llvm::ExecWait(const char * const old_argv[],
248 const char * const old_envp[]) {
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000249#ifdef HAVE_SYS_WAIT_H
John Criswelle5b3e152003-09-17 19:02:49 +0000250 // Create local versions of the parameters that can be passed into execve()
251 // without creating const problems.
John Criswelle5b3e152003-09-17 19:02:49 +0000252 char ** const argv = (char ** const) old_argv;
253 char ** const envp = (char ** const) old_envp;
John Criswell5afb5f62003-09-17 15:13:59 +0000254
John Criswell5afb5f62003-09-17 15:13:59 +0000255 // Create a child process.
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000256 switch (fork()) {
John Criswelle5b3e152003-09-17 19:02:49 +0000257 // An error occured: Return to the caller.
John Criswell5afb5f62003-09-17 15:13:59 +0000258 case -1:
259 return 1;
260 break;
261
John Criswelle5b3e152003-09-17 19:02:49 +0000262 // Child process: Execute the program.
John Criswell5afb5f62003-09-17 15:13:59 +0000263 case 0:
John Criswelle5b3e152003-09-17 19:02:49 +0000264 execve (argv[0], argv, envp);
John Criswelle5b3e152003-09-17 19:02:49 +0000265 // If the execve() failed, we should exit and let the parent pick up
266 // our non-zero exit status.
John Criswelle5b3e152003-09-17 19:02:49 +0000267 exit (1);
John Criswell5afb5f62003-09-17 15:13:59 +0000268
John Criswelle5b3e152003-09-17 19:02:49 +0000269 // Parent process: Break out of the switch to do our processing.
John Criswell5afb5f62003-09-17 15:13:59 +0000270 default:
271 break;
272 }
273
Misha Brukmand6af6862004-06-02 00:09:46 +0000274 // Parent process: Wait for the child process to terminate.
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000275 int status;
John Criswell5afb5f62003-09-17 15:13:59 +0000276 if ((wait (&status)) == -1)
John Criswell5afb5f62003-09-17 15:13:59 +0000277 return 1;
John Criswell5afb5f62003-09-17 15:13:59 +0000278
John Criswell5afb5f62003-09-17 15:13:59 +0000279 // If the program exited normally with a zero exit status, return success!
John Criswell5afb5f62003-09-17 15:13:59 +0000280 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
John Criswell5afb5f62003-09-17 15:13:59 +0000281 return 0;
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000282#else
283 std::cerr << "llvm::ExecWait not implemented on this platform!\n";
284#endif
John Criswell5afb5f62003-09-17 15:13:59 +0000285
John Criswell5afb5f62003-09-17 15:13:59 +0000286 // Otherwise, return failure.
John Criswell5afb5f62003-09-17 15:13:59 +0000287 return 1;
288}
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000289
290/// AllocateRWXMemory - Allocate a slab of memory with read/write/execute
291/// permissions. This is typically used for JIT applications where we want
292/// to emit code to the memory then jump to it. Getting this type of memory
293/// is very OS specific.
294///
295void *llvm::AllocateRWXMemory(unsigned NumBytes) {
296 if (NumBytes == 0) return 0;
Chris Lattner49f61c42004-05-28 01:20:58 +0000297
298#if defined(HAVE_WINDOWS_H)
299 // On windows we use VirtualAlloc.
300 void *P = VirtualAlloc(0, NumBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
301 if (P == 0) {
302 std::cerr << "Error allocating executable memory!\n";
303 abort();
304 }
305 return P;
306
307#elif defined(HAVE_MMAP)
Misha Brukmanb4873032004-06-18 15:34:07 +0000308 static const long pageSize = GetPageSize();
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000309 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
310
311/* FIXME: This should use the proper autoconf flags */
312#if defined(i386) || defined(__i386__) || defined(__x86__)
313 /* Linux and *BSD tend to have these flags named differently. */
314#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
315# define MAP_ANONYMOUS MAP_ANON
316#endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
317#elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
318/* nothing */
319#else
Chris Lattner49f61c42004-05-28 01:20:58 +0000320 std::cerr << "This architecture has an unknown MMAP implementation!\n";
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000321 abort();
322 return 0;
323#endif
324
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000325 int fd = -1;
326#if defined(__linux__)
327 fd = 0;
328#endif
329
330 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
331#ifdef MAP_NORESERVE
332 mmapFlags |= MAP_NORESERVE;
333#endif
334
335 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
336 mmapFlags, fd, 0);
337 if (pa == MAP_FAILED) {
338 perror("mmap");
339 abort();
340 }
341 return pa;
342#else
343 std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";
344 abort();
345 return 0;
346#endif
347}
348
349