Program.inc 14 KB

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