2
0

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