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