LLVM API Documentation

Unix/Program.inc

Go to the documentation of this file.
00001 //===- llvm/System/Unix/Program.cpp -----------------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Unix specific portion of the Program class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 //===----------------------------------------------------------------------===//
00015 //=== WARNING: Implementation here must contain only generic UNIX code that
00016 //===          is guaranteed to work on *all* UNIX variants.
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include <llvm/Config/config.h>
00020 #include "Unix.h"
00021 #if HAVE_SYS_STAT_H
00022 #include <sys/stat.h>
00023 #endif
00024 #if HAVE_SYS_RESOURCE_H
00025 #include <sys/resource.h>
00026 #endif
00027 #if HAVE_SIGNAL_H
00028 #include <signal.h>
00029 #endif
00030 #if HAVE_FCNTL_H
00031 #include <fcntl.h>
00032 #endif
00033 
00034 namespace llvm {
00035 using namespace sys;
00036 
00037 Program::Program() : Pid_(0) {}
00038 
00039 Program::~Program() {}
00040 
00041 // This function just uses the PATH environment variable to find the program.
00042 Path
00043 Program::FindProgramByName(const std::string& progName) {
00044 
00045   // Check some degenerate cases
00046   if (progName.length() == 0) // no program
00047     return Path();
00048   Path temp;
00049   if (!temp.set(progName)) // invalid name
00050     return Path();
00051   // Use the given path verbatim if it contains any slashes; this matches
00052   // the behavior of sh(1) and friends.
00053   if (progName.find('/') != std::string::npos)
00054     return temp;
00055 
00056   // At this point, the file name does not contain slashes. Search for it
00057   // through the directories specified in the PATH environment variable.
00058 
00059   // Get the path. If its empty, we can't do anything to find it.
00060   const char *PathStr = getenv("PATH");
00061   if (PathStr == 0)
00062     return Path();
00063 
00064   // Now we have a colon separated list of directories to search; try them.
00065   size_t PathLen = strlen(PathStr);
00066   while (PathLen) {
00067     // Find the first colon...
00068     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
00069 
00070     // Check to see if this first directory contains the executable...
00071     Path FilePath;
00072     if (FilePath.set(std::string(PathStr,Colon))) {
00073       FilePath.appendComponent(progName);
00074       if (FilePath.canExecute())
00075         return FilePath;                    // Found the executable!
00076     }
00077 
00078     // Nope it wasn't in this directory, check the next path in the list!
00079     PathLen -= Colon-PathStr;
00080     PathStr = Colon;
00081 
00082     // Advance past duplicate colons
00083     while (*PathStr == ':') {
00084       PathStr++;
00085       PathLen--;
00086     }
00087   }
00088   return Path();
00089 }
00090 
00091 static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
00092   if (Path == 0)
00093     // Noop
00094     return false;
00095   std::string File;
00096   if (Path->isEmpty())
00097     // Redirect empty paths to /dev/null
00098     File = "/dev/null";
00099   else
00100     File = Path->toString();
00101 
00102   // Open the file
00103   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
00104   if (InFD == -1) {
00105     MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
00106               + (FD == 0 ? "input" : "output"));
00107     return true;
00108   }
00109 
00110   // Install it as the requested FD
00111   if (-1 == dup2(InFD, FD)) {
00112     MakeErrMsg(ErrMsg, "Cannot dup2");
00113     return true;
00114   }
00115   close(InFD);      // Close the original FD
00116   return false;
00117 }
00118 
00119 static bool Timeout = false;
00120 static void TimeOutHandler(int Sig) {
00121   Timeout = true;
00122 }
00123 
00124 static void SetMemoryLimits (unsigned size)
00125 {
00126 #if HAVE_SYS_RESOURCE_H
00127   struct rlimit r;
00128   __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
00129 
00130   // Heap size
00131   getrlimit (RLIMIT_DATA, &r);
00132   r.rlim_cur = limit;
00133   setrlimit (RLIMIT_DATA, &r);
00134 #ifdef RLIMIT_RSS
00135   // Resident set size.
00136   getrlimit (RLIMIT_RSS, &r);
00137   r.rlim_cur = limit;
00138   setrlimit (RLIMIT_RSS, &r);
00139 #endif
00140 #ifdef RLIMIT_AS  // e.g. NetBSD doesn't have it.
00141   // Virtual memory.
00142   getrlimit (RLIMIT_AS, &r);
00143   r.rlim_cur = limit;
00144   setrlimit (RLIMIT_AS, &r);
00145 #endif
00146 #endif
00147 }
00148 
00149 bool
00150 Program::Execute(const Path& path,
00151                  const char** args,
00152                  const char** envp,
00153                  const Path** redirects,
00154                  unsigned memoryLimit,
00155                  std::string* ErrMsg)
00156 {
00157   if (!path.canExecute()) {
00158     if (ErrMsg)
00159       *ErrMsg = path.toString() + " is not executable";
00160     return false;
00161   }
00162 
00163   // Create a child process.
00164   int child = fork();
00165   switch (child) {
00166     // An error occured:  Return to the caller.
00167     case -1:
00168       MakeErrMsg(ErrMsg, "Couldn't fork");
00169       return false;
00170 
00171     // Child process: Execute the program.
00172     case 0: {
00173       // Redirect file descriptors...
00174       if (redirects) {
00175         // Redirect stdin
00176         if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
00177         // Redirect stdout
00178         if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
00179         if (redirects[1] && redirects[2] &&
00180             *(redirects[1]) == *(redirects[2])) {
00181           // If stdout and stderr should go to the same place, redirect stderr
00182           // to the FD already open for stdout.
00183           if (-1 == dup2(1,2)) {
00184             MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
00185             return false;
00186           }
00187         } else {
00188           // Just redirect stderr
00189           if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
00190         }
00191       }
00192 
00193       // Set memory limits
00194       if (memoryLimit!=0) {
00195         SetMemoryLimits(memoryLimit);
00196       }
00197 
00198       // Execute!
00199       if (envp != 0)
00200         execve(path.c_str(), (char**)args, (char**)envp);
00201       else
00202         execv(path.c_str(), (char**)args);
00203       // If the execve() failed, we should exit. Follow Unix protocol and
00204       // return 127 if the executable was not found, and 126 otherwise.
00205       // Use _exit rather than exit so that atexit functions and static
00206       // object destructors cloned from the parent process aren't
00207       // redundantly run, and so that any data buffered in stdio buffers
00208       // cloned from the parent aren't redundantly written out.
00209       _exit(errno == ENOENT ? 127 : 126);
00210     }
00211 
00212     // Parent process: Break out of the switch to do our processing.
00213     default:
00214       break;
00215   }
00216 
00217   Pid_ = child;
00218 
00219   return true;
00220 }
00221 
00222 int
00223 Program::Wait(unsigned secondsToWait,
00224               std::string* ErrMsg)
00225 {
00226 #ifdef HAVE_SYS_WAIT_H
00227   struct sigaction Act, Old;
00228 
00229   if (Pid_ == 0) {
00230     MakeErrMsg(ErrMsg, "Process not started!");
00231     return -1;
00232   }
00233 
00234   // Install a timeout handler.
00235   if (secondsToWait) {
00236     Timeout = false;
00237     Act.sa_sigaction = 0;
00238     Act.sa_handler = TimeOutHandler;
00239     sigemptyset(&Act.sa_mask);
00240     Act.sa_flags = 0;
00241     sigaction(SIGALRM, &Act, &Old);
00242     alarm(secondsToWait);
00243   }
00244 
00245   // Parent process: Wait for the child process to terminate.
00246   int status;
00247   int child = this->Pid_;
00248   while (wait(&status) != child)
00249     if (secondsToWait && errno == EINTR) {
00250       // Kill the child.
00251       kill(child, SIGKILL);
00252 
00253       // Turn off the alarm and restore the signal handler
00254       alarm(0);
00255       sigaction(SIGALRM, &Old, 0);
00256 
00257       // Wait for child to die
00258       if (wait(&status) != child)
00259         MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
00260       else
00261         MakeErrMsg(ErrMsg, "Child timed out", 0);
00262 
00263       return -1;   // Timeout detected
00264     } else if (errno != EINTR) {
00265       MakeErrMsg(ErrMsg, "Error waiting for child process");
00266       return -1;
00267     }
00268 
00269   // We exited normally without timeout, so turn off the timer.
00270   if (secondsToWait) {
00271     alarm(0);
00272     sigaction(SIGALRM, &Old, 0);
00273   }
00274 
00275   // Return the proper exit status. 0=success, >0 is programs' exit status,
00276   // <0 means a signal was returned, -9999999 means the program dumped core.
00277   int result = 0;
00278   if (WIFEXITED(status))
00279     result = WEXITSTATUS(status);
00280   else if (WIFSIGNALED(status))
00281     result = 0 - WTERMSIG(status);
00282 #ifdef WCOREDUMP
00283   else if (WCOREDUMP(status))
00284     result |= 0x01000000;
00285 #endif
00286   return result;
00287 #else
00288   return -99;
00289 #endif
00290 
00291 }
00292 
00293 bool Program::ChangeStdinToBinary(){
00294   // Do nothing, as Unix doesn't differentiate between text and binary.
00295   return false;
00296 }
00297 
00298 bool Program::ChangeStdoutToBinary(){
00299   // Do nothing, as Unix doesn't differentiate between text and binary.
00300   return false;
00301 }
00302 
00303 }