Don't use 'using std::error_code' in include/llvm.
[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/Config/config.h>
23 #if HAVE_SYS_STAT_H
24 #include <sys/stat.h>
25 #endif
26 #if HAVE_SYS_RESOURCE_H
27 #include <sys/resource.h>
28 #endif
29 #if HAVE_SIGNAL_H
30 #include <signal.h>
31 #endif
32 #if HAVE_FCNTL_H
33 #include <fcntl.h>
34 #endif
35 #if HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #ifdef HAVE_POSIX_SPAWN
39 #ifdef __sun__
40 #define  _RESTRICT_KYWD
41 #endif
42 #include <spawn.h>
43 #if !defined(__APPLE__)
44   extern char **environ;
45 #else
46 #include <crt_externs.h> // _NSGetEnviron
47 #endif
48 #endif
49
50 namespace llvm {
51 using std::error_code;
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     ChildPid = -1; // mimic a wait() using waitpid()
339   } else if (SecondsToWait) {
340     // Install a timeout handler.  The handler itself does nothing, but the
341     // simple fact of having a handler at all causes the wait below to return
342     // with EINTR, unlike if we used SIG_IGN.
343     memset(&Act, 0, sizeof(Act));
344     Act.sa_handler = TimeOutHandler;
345     sigemptyset(&Act.sa_mask);
346     sigaction(SIGALRM, &Act, &Old);
347     alarm(SecondsToWait);
348   } else if (SecondsToWait == 0)
349     WaitPidOptions = WNOHANG;
350
351   // Parent process: Wait for the child process to terminate.
352   int status;
353   ProcessInfo WaitResult;
354   WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
355   if (WaitResult.Pid != PI.Pid) {
356     if (WaitResult.Pid == 0) {
357       // Non-blocking wait.
358       return WaitResult;
359     } else {
360       if (SecondsToWait && errno == EINTR) {
361         // Kill the child.
362         kill(PI.Pid, SIGKILL);
363
364         // Turn off the alarm and restore the signal handler
365         alarm(0);
366         sigaction(SIGALRM, &Old, nullptr);
367
368         // Wait for child to die
369         if (wait(&status) != ChildPid)
370           MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
371         else
372           MakeErrMsg(ErrMsg, "Child timed out", 0);
373
374         WaitResult.ReturnCode = -2; // Timeout detected
375         return WaitResult;
376       } else if (errno != EINTR) {
377         MakeErrMsg(ErrMsg, "Error waiting for child process");
378         WaitResult.ReturnCode = -1;
379         return WaitResult;
380       }
381     }
382   }
383
384   // We exited normally without timeout, so turn off the timer.
385   if (SecondsToWait && !WaitUntilTerminates) {
386     alarm(0);
387     sigaction(SIGALRM, &Old, nullptr);
388   }
389
390   // Return the proper exit status. Detect error conditions
391   // so we can return -1 for them and set ErrMsg informatively.
392   int result = 0;
393   if (WIFEXITED(status)) {
394     result = WEXITSTATUS(status);
395     WaitResult.ReturnCode = result;
396
397     if (result == 127) {
398       if (ErrMsg)
399         *ErrMsg = llvm::sys::StrError(ENOENT);
400       WaitResult.ReturnCode = -1;
401       return WaitResult;
402     }
403     if (result == 126) {
404       if (ErrMsg)
405         *ErrMsg = "Program could not be executed";
406       WaitResult.ReturnCode = -1;
407       return WaitResult;
408     }
409   } else if (WIFSIGNALED(status)) {
410     if (ErrMsg) {
411       *ErrMsg = strsignal(WTERMSIG(status));
412 #ifdef WCOREDUMP
413       if (WCOREDUMP(status))
414         *ErrMsg += " (core dumped)";
415 #endif
416     }
417     // Return a special value to indicate that the process received an unhandled
418     // signal during execution as opposed to failing to execute.
419     WaitResult.ReturnCode = -2;
420   }
421 #else
422   if (ErrMsg)
423     *ErrMsg = "Program::Wait is not implemented on this platform yet!";
424   ProcessInfo WaitResult;
425   WaitResult.ReturnCode = -2;
426 #endif
427   return WaitResult;
428 }
429
430 error_code sys::ChangeStdinToBinary(){
431   // Do nothing, as Unix doesn't differentiate between text and binary.
432   return error_code();
433 }
434
435 error_code sys::ChangeStdoutToBinary(){
436   // Do nothing, as Unix doesn't differentiate between text and binary.
437   return error_code();
438 }
439
440 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
441   static long ArgMax = sysconf(_SC_ARG_MAX);
442
443   // System says no practical limit.
444   if (ArgMax == -1)
445     return true;
446
447   // Conservatively account for space required by environment variables.
448   ArgMax /= 2;
449
450   size_t ArgLength = 0;
451   for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
452        I != E; ++I) {
453     ArgLength += strlen(*I) + 1;
454     if (ArgLength > size_t(ArgMax)) {
455       return false;
456     }
457   }
458   return true;
459 }
460 }