1//===- llvm/Support/Unix/Program.cpp -----------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Unix specific portion of the Program class.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic UNIX code that
16//===          is guaranteed to work on *all* UNIX variants.
17//===----------------------------------------------------------------------===//
18
19#include "Unix.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/Support/FileSystem.h"
23#include "llvm/Support/raw_ostream.h"
24#include <llvm/Config/config.h>
25#if HAVE_SYS_STAT_H
26#include <sys/stat.h>
27#endif
28#if HAVE_SYS_RESOURCE_H
29#include <sys/resource.h>
30#endif
31#if HAVE_SIGNAL_H
32#include <signal.h>
33#endif
34#if HAVE_FCNTL_H
35#include <fcntl.h>
36#endif
37#if HAVE_UNISTD_H
38#include <unistd.h>
39#endif
40#ifdef HAVE_POSIX_SPAWN
41#ifdef __sun__
42#define  _RESTRICT_KYWD
43#endif
44#include <spawn.h>
45#if !defined(__APPLE__)
46  extern char **environ;
47#else
48#include <crt_externs.h> // _NSGetEnviron
49#endif
50#endif
51
52namespace llvm {
53
54using namespace sys;
55
56ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
57
58ErrorOr<std::string> sys::findProgramByName(StringRef Name,
59                                            ArrayRef<StringRef> Paths) {
60  assert(!Name.empty() && "Must have a name!");
61  // Use the given path verbatim if it contains any slashes; this matches
62  // the behavior of sh(1) and friends.
63  if (Name.find('/') != StringRef::npos)
64    return std::string(Name);
65
66  SmallVector<StringRef, 16> EnvironmentPaths;
67  if (Paths.empty())
68    if (const char *PathEnv = std::getenv("PATH")) {
69      SplitString(PathEnv, EnvironmentPaths, ":");
70      Paths = EnvironmentPaths;
71    }
72
73  for (auto Path : Paths) {
74    if (Path.empty())
75      continue;
76
77    // Check to see if this first directory contains the executable...
78    SmallString<128> FilePath(Path);
79    sys::path::append(FilePath, Name);
80    if (sys::fs::can_execute(FilePath.c_str()))
81      return std::string(FilePath.str()); // Found the executable!
82  }
83  return std::errc::no_such_file_or_directory;
84}
85
86static bool RedirectIO(const StringRef *Path, int FD, std::string* ErrMsg) {
87  if (!Path) // Noop
88    return false;
89  std::string File;
90  if (Path->empty())
91    // Redirect empty paths to /dev/null
92    File = "/dev/null";
93  else
94    File = *Path;
95
96  // Open the file
97  int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
98  if (InFD == -1) {
99    MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
100              + (FD == 0 ? "input" : "output"));
101    return true;
102  }
103
104  // Install it as the requested FD
105  if (dup2(InFD, FD) == -1) {
106    MakeErrMsg(ErrMsg, "Cannot dup2");
107    close(InFD);
108    return true;
109  }
110  close(InFD);      // Close the original FD
111  return false;
112}
113
114#ifdef HAVE_POSIX_SPAWN
115static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
116                          posix_spawn_file_actions_t *FileActions) {
117  if (!Path) // Noop
118    return false;
119  const char *File;
120  if (Path->empty())
121    // Redirect empty paths to /dev/null
122    File = "/dev/null";
123  else
124    File = Path->c_str();
125
126  if (int Err = posix_spawn_file_actions_addopen(
127          FileActions, FD, File,
128          FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
129    return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
130  return false;
131}
132#endif
133
134static void TimeOutHandler(int Sig) {
135}
136
137static void SetMemoryLimits (unsigned size)
138{
139#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
140  struct rlimit r;
141  __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
142
143  // Heap size
144  getrlimit (RLIMIT_DATA, &r);
145  r.rlim_cur = limit;
146  setrlimit (RLIMIT_DATA, &r);
147#ifdef RLIMIT_RSS
148  // Resident set size.
149  getrlimit (RLIMIT_RSS, &r);
150  r.rlim_cur = limit;
151  setrlimit (RLIMIT_RSS, &r);
152#endif
153#ifdef RLIMIT_AS  // e.g. NetBSD doesn't have it.
154  // Don't set virtual memory limit if built with any Sanitizer. They need 80Tb
155  // of virtual memory for shadow memory mapping.
156#if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD
157  // Virtual memory.
158  getrlimit (RLIMIT_AS, &r);
159  r.rlim_cur = limit;
160  setrlimit (RLIMIT_AS, &r);
161#endif
162#endif
163#endif
164}
165
166}
167
168static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
169                    const char **envp, const StringRef **redirects,
170                    unsigned memoryLimit, std::string *ErrMsg) {
171  if (!llvm::sys::fs::exists(Program)) {
172    if (ErrMsg)
173      *ErrMsg = std::string("Executable \"") + Program.str() +
174                std::string("\" doesn't exist!");
175    return false;
176  }
177
178  // If this OS has posix_spawn and there is no memory limit being implied, use
179  // posix_spawn.  It is more efficient than fork/exec.
180#ifdef HAVE_POSIX_SPAWN
181  if (memoryLimit == 0) {
182    posix_spawn_file_actions_t FileActionsStore;
183    posix_spawn_file_actions_t *FileActions = nullptr;
184
185    // If we call posix_spawn_file_actions_addopen we have to make sure the
186    // c strings we pass to it stay alive until the call to posix_spawn,
187    // so we copy any StringRefs into this variable.
188    std::string RedirectsStorage[3];
189
190    if (redirects) {
191      std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
192      for (int I = 0; I < 3; ++I) {
193        if (redirects[I]) {
194          RedirectsStorage[I] = *redirects[I];
195          RedirectsStr[I] = &RedirectsStorage[I];
196        }
197      }
198
199      FileActions = &FileActionsStore;
200      posix_spawn_file_actions_init(FileActions);
201
202      // Redirect stdin/stdout.
203      if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
204          RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
205        return false;
206      if (redirects[1] == nullptr || redirects[2] == nullptr ||
207          *redirects[1] != *redirects[2]) {
208        // Just redirect stderr
209        if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
210          return false;
211      } else {
212        // If stdout and stderr should go to the same place, redirect stderr
213        // to the FD already open for stdout.
214        if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
215          return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
216      }
217    }
218
219    if (!envp)
220#if !defined(__APPLE__)
221      envp = const_cast<const char **>(environ);
222#else
223      // environ is missing in dylibs.
224      envp = const_cast<const char **>(*_NSGetEnviron());
225#endif
226
227    // Explicitly initialized to prevent what appears to be a valgrind false
228    // positive.
229    pid_t PID = 0;
230    int Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
231                          /*attrp*/nullptr, const_cast<char **>(args),
232                          const_cast<char **>(envp));
233
234    if (FileActions)
235      posix_spawn_file_actions_destroy(FileActions);
236
237    if (Err)
238     return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
239
240    PI.Pid = PID;
241
242    return true;
243  }
244#endif
245
246  // Create a child process.
247  int child = fork();
248  switch (child) {
249    // An error occurred:  Return to the caller.
250    case -1:
251      MakeErrMsg(ErrMsg, "Couldn't fork");
252      return false;
253
254    // Child process: Execute the program.
255    case 0: {
256      // Redirect file descriptors...
257      if (redirects) {
258        // Redirect stdin
259        if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
260        // Redirect stdout
261        if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
262        if (redirects[1] && redirects[2] &&
263            *(redirects[1]) == *(redirects[2])) {
264          // If stdout and stderr should go to the same place, redirect stderr
265          // to the FD already open for stdout.
266          if (-1 == dup2(1,2)) {
267            MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
268            return false;
269          }
270        } else {
271          // Just redirect stderr
272          if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
273        }
274      }
275
276      // Set memory limits
277      if (memoryLimit!=0) {
278        SetMemoryLimits(memoryLimit);
279      }
280
281      // Execute!
282      std::string PathStr = Program;
283      if (envp != nullptr)
284        execve(PathStr.c_str(),
285               const_cast<char **>(args),
286               const_cast<char **>(envp));
287      else
288        execv(PathStr.c_str(),
289              const_cast<char **>(args));
290      // If the execve() failed, we should exit. Follow Unix protocol and
291      // return 127 if the executable was not found, and 126 otherwise.
292      // Use _exit rather than exit so that atexit functions and static
293      // object destructors cloned from the parent process aren't
294      // redundantly run, and so that any data buffered in stdio buffers
295      // cloned from the parent aren't redundantly written out.
296      _exit(errno == ENOENT ? 127 : 126);
297    }
298
299    // Parent process: Break out of the switch to do our processing.
300    default:
301      break;
302  }
303
304  PI.Pid = child;
305
306  return true;
307}
308
309namespace llvm {
310
311ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
312                      bool WaitUntilTerminates, std::string *ErrMsg) {
313#ifdef HAVE_SYS_WAIT_H
314  struct sigaction Act, Old;
315  assert(PI.Pid && "invalid pid to wait on, process not started?");
316
317  int WaitPidOptions = 0;
318  pid_t ChildPid = PI.Pid;
319  if (WaitUntilTerminates) {
320    SecondsToWait = 0;
321  } else if (SecondsToWait) {
322    // Install a timeout handler.  The handler itself does nothing, but the
323    // simple fact of having a handler at all causes the wait below to return
324    // with EINTR, unlike if we used SIG_IGN.
325    memset(&Act, 0, sizeof(Act));
326    Act.sa_handler = TimeOutHandler;
327    sigemptyset(&Act.sa_mask);
328    sigaction(SIGALRM, &Act, &Old);
329    alarm(SecondsToWait);
330  } else if (SecondsToWait == 0)
331    WaitPidOptions = WNOHANG;
332
333  // Parent process: Wait for the child process to terminate.
334  int status;
335  ProcessInfo WaitResult;
336
337  do {
338    WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
339  } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
340
341  if (WaitResult.Pid != PI.Pid) {
342    if (WaitResult.Pid == 0) {
343      // Non-blocking wait.
344      return WaitResult;
345    } else {
346      if (SecondsToWait && errno == EINTR) {
347        // Kill the child.
348        kill(PI.Pid, SIGKILL);
349
350        // Turn off the alarm and restore the signal handler
351        alarm(0);
352        sigaction(SIGALRM, &Old, nullptr);
353
354        // Wait for child to die
355        if (wait(&status) != ChildPid)
356          MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
357        else
358          MakeErrMsg(ErrMsg, "Child timed out", 0);
359
360        WaitResult.ReturnCode = -2; // Timeout detected
361        return WaitResult;
362      } else if (errno != EINTR) {
363        MakeErrMsg(ErrMsg, "Error waiting for child process");
364        WaitResult.ReturnCode = -1;
365        return WaitResult;
366      }
367    }
368  }
369
370  // We exited normally without timeout, so turn off the timer.
371  if (SecondsToWait && !WaitUntilTerminates) {
372    alarm(0);
373    sigaction(SIGALRM, &Old, nullptr);
374  }
375
376  // Return the proper exit status. Detect error conditions
377  // so we can return -1 for them and set ErrMsg informatively.
378  int result = 0;
379  if (WIFEXITED(status)) {
380    result = WEXITSTATUS(status);
381    WaitResult.ReturnCode = result;
382
383    if (result == 127) {
384      if (ErrMsg)
385        *ErrMsg = llvm::sys::StrError(ENOENT);
386      WaitResult.ReturnCode = -1;
387      return WaitResult;
388    }
389    if (result == 126) {
390      if (ErrMsg)
391        *ErrMsg = "Program could not be executed";
392      WaitResult.ReturnCode = -1;
393      return WaitResult;
394    }
395  } else if (WIFSIGNALED(status)) {
396    if (ErrMsg) {
397      *ErrMsg = strsignal(WTERMSIG(status));
398#ifdef WCOREDUMP
399      if (WCOREDUMP(status))
400        *ErrMsg += " (core dumped)";
401#endif
402    }
403    // Return a special value to indicate that the process received an unhandled
404    // signal during execution as opposed to failing to execute.
405    WaitResult.ReturnCode = -2;
406  }
407#else
408  if (ErrMsg)
409    *ErrMsg = "Program::Wait is not implemented on this platform yet!";
410  ProcessInfo WaitResult;
411  WaitResult.ReturnCode = -2;
412#endif
413  return WaitResult;
414}
415
416  std::error_code sys::ChangeStdinToBinary(){
417  // Do nothing, as Unix doesn't differentiate between text and binary.
418    return std::error_code();
419}
420
421  std::error_code sys::ChangeStdoutToBinary(){
422  // Do nothing, as Unix doesn't differentiate between text and binary.
423    return std::error_code();
424}
425
426std::error_code
427llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
428                                 WindowsEncodingMethod Encoding /*unused*/) {
429  std::error_code EC;
430  llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
431
432  if (EC)
433    return EC;
434
435  OS << Contents;
436
437  if (OS.has_error())
438    return std::make_error_code(std::errc::io_error);
439
440  return EC;
441}
442
443bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
444  static long ArgMax = sysconf(_SC_ARG_MAX);
445
446  // System says no practical limit.
447  if (ArgMax == -1)
448    return true;
449
450  // Conservatively account for space required by environment variables.
451  long HalfArgMax = ArgMax / 2;
452
453  size_t ArgLength = 0;
454  for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
455       I != E; ++I) {
456    ArgLength += strlen(*I) + 1;
457    if (ArgLength > size_t(HalfArgMax)) {
458      return false;
459    }
460  }
461  return true;
462}
463}
464