Instruction select globals with offsets better. For example, on this test
[oota-llvm.git] / lib / Support / SystemUtils.cpp
index e1af3f92cecb7ad6c4b7f1034769a42e698d8fb6..3b529df79c75b77800b5cf2bd2f00bb27aee2c3d 100644 (file)
@@ -1,26 +1,39 @@
-//===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===//
+//===- SystemUtils.cpp - Utilities for low-level system tasks -------------===//
+// 
+//                     The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// 
+//===----------------------------------------------------------------------===//
 //
 // This file contains functions used to do a variety of low-level, often
 // system-specific, tasks.
 //
 //===----------------------------------------------------------------------===//
 
-#include "Support/SystemUtils.h"
+#define _POSIX_MAPPED_FILES
+#include "llvm/Support/SystemUtils.h"
+#include "llvm/Config/fcntl.h"
+#include "llvm/Config/pagesize.h"
+#include "llvm/Config/unistd.h"
+#include "llvm/Config/windows.h"
+#include "llvm/Config/sys/mman.h"
+#include "llvm/Config/sys/stat.h"
+#include "llvm/Config/sys/types.h"
+#include "llvm/Config/sys/wait.h"
 #include <algorithm>
+#include <cerrno>
+#include <cstdlib>
 #include <fstream>
 #include <iostream>
-#include <cstdlib>
-#include "Config/sys/types.h"
-#include "Config/sys/stat.h"
-#include "Config/fcntl.h"
-#include "Config/sys/wait.h"
-#include "Config/unistd.h"
-#include "Config/errno.h"
+#include <signal.h>
+using namespace llvm;
 
 /// isExecutableFile - This function returns true if the filename specified
 /// exists and is executable.
 ///
-bool isExecutableFile(const std::string &ExeFileName) {
+bool llvm::isExecutableFile(const std::string &ExeFileName) {
   struct stat Buf;
   if (stat(ExeFileName.c_str(), &Buf))
     return false;  // Must not be executable!
@@ -36,14 +49,26 @@ bool isExecutableFile(const std::string &ExeFileName) {
     return Buf.st_mode & S_IXOTH;
 }
 
+/// isStandardOutAConsole - Return true if we can tell that the standard output
+/// stream goes to a terminal window or console.
+bool llvm::isStandardOutAConsole() {
+#if HAVE_ISATTY
+  return isatty(1);
+#endif
+  // If we don't have isatty, just return false.
+  return false;
+}
+
+
 /// FindExecutable - Find a named executable, giving the argv[0] of program
 /// being executed. This allows us to find another LLVM tool if it is built
 /// into the same directory, but that directory is neither the current
 /// directory, nor in the PATH.  If the executable cannot be found, return an
 /// empty string.
 /// 
-std::string FindExecutable(const std::string &ExeName,
-                           const std::string &ProgramPath) {
+#undef FindExecutable   // needed on windows :(
+std::string llvm::FindExecutable(const std::string &ExeName,
+                                 const std::string &ProgramPath) {
   // First check the directory that bugpoint is in.  We can do this if
   // BugPointPath contains at least one / character, indicating that it is a
   // relative path to bugpoint itself.
@@ -101,19 +126,24 @@ static void RedirectFD(const std::string &File, int FD) {
   close(InFD);      // Close the original FD
 }
 
+static bool Timeout = false;
+static void TimeOutHandler(int Sig) {
+  Timeout = true;
+}
+
 /// RunProgramWithTimeout - This function executes the specified program, with
 /// the specified null-terminated argument array, with the stdin/out/err fd's
-/// redirected, with a timeout specified on the command line.  This terminates
+/// redirected, with a timeout specified by the last argument.  This terminates
 /// the calling program if there is an error executing the specified program.
 /// It returns the return value of the program, or -1 if a timeout is detected.
 ///
-int RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,
-                          const std::string &StdInFile,
-                          const std::string &StdOutFile,
-                          const std::string &StdErrFile) {
-
-  // FIXME: install sigalarm handler here for timeout...
-
+int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
+                                const char **Args,
+                                const std::string &StdInFile,
+                                const std::string &StdOutFile,
+                                const std::string &StdErrFile,
+                                unsigned NumSeconds) {
+#ifdef HAVE_SYS_WAIT_H
   int Child = fork();
   switch (Child) {
   case -1:
@@ -122,7 +152,10 @@ int RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,
   case 0:               // Child
     RedirectFD(StdInFile, 0);      // Redirect file descriptors...
     RedirectFD(StdOutFile, 1);
-    RedirectFD(StdErrFile, 2);
+    if (StdOutFile != StdErrFile)
+      RedirectFD(StdErrFile, 2);
+    else
+      dup2(1, 2);
 
     execv(ProgramPath.c_str(), (char *const *)Args);
     std::cerr << "Error executing program: '" << ProgramPath;
@@ -137,35 +170,51 @@ int RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,
   // Make sure all output has been written while waiting
   std::cout << std::flush;
 
+  // Install a timeout handler.
+  Timeout = false;
+  struct sigaction Act, Old;
+  Act.sa_sigaction = 0;
+  Act.sa_handler = TimeOutHandler;
+  sigemptyset(&Act.sa_mask);
+  Act.sa_flags = 0;
+  sigaction(SIGALRM, &Act, &Old);
+
+  // Set the timeout if one is set.
+  if (NumSeconds)
+    alarm(NumSeconds);
+
   int Status;
-  if (wait(&Status) != Child) {
+  while (wait(&Status) != Child)
     if (errno == EINTR) {
-      static bool FirstTimeout = true;
-      if (FirstTimeout) {
-        std::cout <<
- "*** Program execution timed out!  This mechanism is designed to handle\n"
- "    programs stuck in infinite loops gracefully.  The -timeout option\n"
- "    can be used to change the timeout threshold or disable it completely\n"
- "    (with -timeout=0).  This message is only displayed once.\n";
-        FirstTimeout = false;
+      if (Timeout) {
+        // Kill the child.
+        kill(Child, SIGKILL);
+        
+        if (wait(&Status) != Child)
+          std::cerr << "Something funny happened waiting for the child!\n";
+        
+        alarm(0);
+        sigaction(SIGALRM, &Old, 0);
+        return -1;   // Timeout detected
+      } else {
+        std::cerr << "Error waiting for child process!\n";
+        exit(1);
       }
-      return -1;   // Timeout detected
     }
 
-    std::cerr << "Error waiting for child process!\n";
-    exit(1);
-  }
+  alarm(0);
+  sigaction(SIGALRM, &Old, 0);
   return Status;
+
+#else
+  std::cerr << "RunProgramWithTimeout not implemented on this platform!\n";
+  return -1;
+#endif
 }
 
 
-//
-// Function: ExecWait ()
-//
-// Description:
-//  This function executes a program with the specified arguments and
-//  environment.  It then waits for the progarm to termiante and then returns
-//  to the caller.
+// ExecWait - executes a program with the specified arguments and environment.
+// It then waits for the progarm to termiante and then returns to the caller.
 //
 // Inputs:
 //  argv - The arguments to the program as an array of C strings.  The first
@@ -195,73 +244,106 @@ int RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,
 //
 //  This function does not use $PATH to find programs.
 //
-int
-ExecWait (const char * const old_argv[], const char * const old_envp[])
-{
-  // Child process ID
-  register int child;
-
-  // Status from child process when it exits
-  int status;
-  //
+int llvm::ExecWait(const char * const old_argv[],
+                   const char * const old_envp[]) {
+#ifdef HAVE_SYS_WAIT_H
   // Create local versions of the parameters that can be passed into execve()
   // without creating const problems.
-  //
   char ** const argv = (char ** const) old_argv;
   char ** const envp = (char ** const) old_envp;
 
-  //
   // Create a child process.
-  //
-  switch (child=fork())
-  {
-    //
+  switch (fork()) {
     // An error occured:  Return to the caller.
-    //
     case -1:
       return 1;
       break;
 
-    //
     // Child process: Execute the program.
-    //
     case 0:
       execve (argv[0], argv, envp);
-
-      //
       // If the execve() failed, we should exit and let the parent pick up
       // our non-zero exit status.
-      //
       exit (1);
-      break;
 
-    //
     // Parent process: Break out of the switch to do our processing.
-    //
     default:
       break;
   }
 
-  //
-  // Parent process: Wait for the child process to termiante.
-  //
+  // Parent process: Wait for the child process to terminate.
+  int status;
   if ((wait (&status)) == -1)
-  {
     return 1;
-  }
 
-  //
   // If the program exited normally with a zero exit status, return success!
-  //
   if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
-  {
     return 0;
-  }
+#else
+  std::cerr << "llvm::ExecWait not implemented on this platform!\n";
+#endif
 
-  //
   // Otherwise, return failure.
-  //
   return 1;
 }
 
+/// AllocateRWXMemory - Allocate a slab of memory with read/write/execute
+/// permissions.  This is typically used for JIT applications where we want
+/// to emit code to the memory then jump to it.  Getting this type of memory
+/// is very OS specific.
+///
+void *llvm::AllocateRWXMemory(unsigned NumBytes) {
+  if (NumBytes == 0) return 0;
+
+#if defined(HAVE_WINDOWS_H)
+  // On windows we use VirtualAlloc.
+  void *P = VirtualAlloc(0, NumBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
+  if (P == 0) {
+    std::cerr << "Error allocating executable memory!\n";
+    abort();
+  }
+  return P;
+
+#elif defined(HAVE_MMAP)
+  static const long pageSize = GetPageSize();
+  unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
+
+/* FIXME: This should use the proper autoconf flags */
+#if defined(i386) || defined(__i386__) || defined(__x86__)
+  /* Linux and *BSD tend to have these flags named differently. */
+#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
+# define MAP_ANONYMOUS MAP_ANON
+#endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
+#elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
+/* nothing */
+#else
+  std::cerr << "This architecture has an unknown MMAP implementation!\n";
+  abort();
+  return 0;
+#endif
+
+  int fd = -1;
+#if defined(__linux__)
+  fd = 0;
+#endif
+
+  unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
+#ifdef MAP_NORESERVE
+  mmapFlags |= MAP_NORESERVE;
+#endif
+
+  void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
+                  mmapFlags, fd, 0);
+  if (pa == MAP_FAILED) {
+    perror("mmap");
+    abort();
+  }
+  return pa;
+#else
+  std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";
+  abort();
+  return 0;
+#endif
+}
+
+