OSDN Git Service

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