Program.inc 14 KB

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