Program.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. //===- llvm/Support/Unix/Program.cpp -----------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Unix specific portion of the Program class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. //===----------------------------------------------------------------------===//
  13. //=== WARNING: Implementation here must contain only generic UNIX code that
  14. //=== is guaranteed to work on *all* UNIX variants.
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Support/Program.h"
  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/StringSaver.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #if HAVE_SYS_STAT_H
  27. #include <sys/stat.h>
  28. #endif
  29. #if HAVE_SYS_RESOURCE_H
  30. #include <sys/resource.h>
  31. #endif
  32. #if HAVE_SIGNAL_H
  33. #include <signal.h>
  34. #endif
  35. #if HAVE_FCNTL_H
  36. #include <fcntl.h>
  37. #endif
  38. #if HAVE_UNISTD_H
  39. #include <unistd.h>
  40. #endif
  41. #ifdef HAVE_POSIX_SPAWN
  42. #include <spawn.h>
  43. #if defined(__APPLE__)
  44. #include <TargetConditionals.h>
  45. #endif
  46. #if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
  47. #define USE_NSGETENVIRON 1
  48. #else
  49. #define USE_NSGETENVIRON 0
  50. #endif
  51. #if !USE_NSGETENVIRON
  52. extern char **environ;
  53. #else
  54. #include <crt_externs.h> // _NSGetEnviron
  55. #endif
  56. #endif
  57. using namespace llvm;
  58. using namespace sys;
  59. ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
  60. ErrorOr<std::string> sys::findProgramByName(StringRef Name,
  61. ArrayRef<StringRef> Paths) {
  62. assert(!Name.empty() && "Must have a name!");
  63. // Use the given path verbatim if it contains any slashes; this matches
  64. // the behavior of sh(1) and friends.
  65. if (Name.contains('/'))
  66. return std::string(Name);
  67. SmallVector<StringRef, 16> EnvironmentPaths;
  68. if (Paths.empty())
  69. if (const char *PathEnv = std::getenv("PATH")) {
  70. SplitString(PathEnv, EnvironmentPaths, ":");
  71. Paths = EnvironmentPaths;
  72. }
  73. for (auto Path : Paths) {
  74. if (Path.empty())
  75. continue;
  76. // Check to see if this first directory contains the executable...
  77. SmallString<128> FilePath(Path);
  78. sys::path::append(FilePath, Name);
  79. if (sys::fs::can_execute(FilePath.c_str()))
  80. return std::string(FilePath.str()); // Found the executable!
  81. }
  82. return errc::no_such_file_or_directory;
  83. }
  84. static bool RedirectIO(Optional<StringRef> Path, int FD, std::string* ErrMsg) {
  85. if (!Path) // Noop
  86. return false;
  87. std::string File;
  88. if (Path->empty())
  89. // Redirect empty paths to /dev/null
  90. File = "/dev/null";
  91. else
  92. File = std::string(*Path);
  93. // Open the file
  94. int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
  95. if (InFD == -1) {
  96. MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
  97. + (FD == 0 ? "input" : "output"));
  98. return true;
  99. }
  100. // Install it as the requested FD
  101. if (dup2(InFD, FD) == -1) {
  102. MakeErrMsg(ErrMsg, "Cannot dup2");
  103. close(InFD);
  104. return true;
  105. }
  106. close(InFD); // Close the original FD
  107. return false;
  108. }
  109. #ifdef HAVE_POSIX_SPAWN
  110. static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
  111. posix_spawn_file_actions_t *FileActions) {
  112. if (!Path) // Noop
  113. return false;
  114. const char *File;
  115. if (Path->empty())
  116. // Redirect empty paths to /dev/null
  117. File = "/dev/null";
  118. else
  119. File = Path->c_str();
  120. if (int Err = posix_spawn_file_actions_addopen(
  121. FileActions, FD, File,
  122. FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
  123. return MakeErrMsg(ErrMsg, "Cannot posix_spawn_file_actions_addopen", Err);
  124. return false;
  125. }
  126. #endif
  127. static void TimeOutHandler(int Sig) {
  128. }
  129. static void SetMemoryLimits(unsigned size) {
  130. #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
  131. struct rlimit r;
  132. __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
  133. // Heap size
  134. getrlimit (RLIMIT_DATA, &r);
  135. r.rlim_cur = limit;
  136. setrlimit (RLIMIT_DATA, &r);
  137. #ifdef RLIMIT_RSS
  138. // Resident set size.
  139. getrlimit (RLIMIT_RSS, &r);
  140. r.rlim_cur = limit;
  141. setrlimit (RLIMIT_RSS, &r);
  142. #endif
  143. #endif
  144. }
  145. static std::vector<const char *>
  146. toNullTerminatedCStringArray(ArrayRef<StringRef> Strings, StringSaver &Saver) {
  147. std::vector<const char *> Result;
  148. for (StringRef S : Strings)
  149. Result.push_back(Saver.save(S).data());
  150. Result.push_back(nullptr);
  151. return Result;
  152. }
  153. static bool Execute(ProcessInfo &PI, StringRef Program,
  154. ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,
  155. ArrayRef<Optional<StringRef>> Redirects,
  156. unsigned MemoryLimit, std::string *ErrMsg,
  157. BitVector *AffinityMask) {
  158. if (!llvm::sys::fs::exists(Program)) {
  159. if (ErrMsg)
  160. *ErrMsg = std::string("Executable \"") + Program.str() +
  161. std::string("\" doesn't exist!");
  162. return false;
  163. }
  164. assert(!AffinityMask && "Starting a process with an affinity mask is "
  165. "currently not supported on Unix!");
  166. BumpPtrAllocator Allocator;
  167. StringSaver Saver(Allocator);
  168. std::vector<const char *> ArgVector, EnvVector;
  169. const char **Argv = nullptr;
  170. const char **Envp = nullptr;
  171. ArgVector = toNullTerminatedCStringArray(Args, Saver);
  172. Argv = ArgVector.data();
  173. if (Env) {
  174. EnvVector = toNullTerminatedCStringArray(*Env, Saver);
  175. Envp = EnvVector.data();
  176. }
  177. // If this OS has posix_spawn and there is no memory limit being implied, use
  178. // posix_spawn. It is more efficient than fork/exec.
  179. #ifdef HAVE_POSIX_SPAWN
  180. if (MemoryLimit == 0) {
  181. posix_spawn_file_actions_t FileActionsStore;
  182. posix_spawn_file_actions_t *FileActions = nullptr;
  183. // If we call posix_spawn_file_actions_addopen we have to make sure the
  184. // c strings we pass to it stay alive until the call to posix_spawn,
  185. // so we copy any StringRefs into this variable.
  186. std::string RedirectsStorage[3];
  187. if (!Redirects.empty()) {
  188. assert(Redirects.size() == 3);
  189. std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
  190. for (int I = 0; I < 3; ++I) {
  191. if (Redirects[I]) {
  192. RedirectsStorage[I] = std::string(*Redirects[I]);
  193. RedirectsStr[I] = &RedirectsStorage[I];
  194. }
  195. }
  196. FileActions = &FileActionsStore;
  197. posix_spawn_file_actions_init(FileActions);
  198. // Redirect stdin/stdout.
  199. if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
  200. RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
  201. return false;
  202. if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
  203. // Just redirect stderr
  204. if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
  205. return false;
  206. } else {
  207. // If stdout and stderr should go to the same place, redirect stderr
  208. // to the FD already open for stdout.
  209. if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
  210. return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
  211. }
  212. }
  213. if (!Envp)
  214. #if !USE_NSGETENVIRON
  215. Envp = const_cast<const char **>(environ);
  216. #else
  217. // environ is missing in dylibs.
  218. Envp = const_cast<const char **>(*_NSGetEnviron());
  219. #endif
  220. constexpr int maxRetries = 8;
  221. int retries = 0;
  222. pid_t PID;
  223. int Err;
  224. do {
  225. PID = 0; // Make Valgrind happy.
  226. Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
  227. /*attrp*/ nullptr, const_cast<char **>(Argv),
  228. const_cast<char **>(Envp));
  229. } while (Err == EINTR && ++retries < maxRetries);
  230. if (FileActions)
  231. posix_spawn_file_actions_destroy(FileActions);
  232. if (Err)
  233. return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
  234. PI.Pid = PID;
  235. PI.Process = PID;
  236. return true;
  237. }
  238. #endif
  239. // Create a child process.
  240. int child = fork();
  241. switch (child) {
  242. // An error occurred: Return to the caller.
  243. case -1:
  244. MakeErrMsg(ErrMsg, "Couldn't fork");
  245. return false;
  246. // Child process: Execute the program.
  247. case 0: {
  248. // Redirect file descriptors...
  249. if (!Redirects.empty()) {
  250. // Redirect stdin
  251. if (RedirectIO(Redirects[0], 0, ErrMsg)) { return false; }
  252. // Redirect stdout
  253. if (RedirectIO(Redirects[1], 1, ErrMsg)) { return false; }
  254. if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
  255. // If stdout and stderr should go to the same place, redirect stderr
  256. // to the FD already open for stdout.
  257. if (-1 == dup2(1,2)) {
  258. MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
  259. return false;
  260. }
  261. } else {
  262. // Just redirect stderr
  263. if (RedirectIO(Redirects[2], 2, ErrMsg)) { return false; }
  264. }
  265. }
  266. // Set memory limits
  267. if (MemoryLimit!=0) {
  268. SetMemoryLimits(MemoryLimit);
  269. }
  270. // Execute!
  271. std::string PathStr = std::string(Program);
  272. if (Envp != nullptr)
  273. execve(PathStr.c_str(), const_cast<char **>(Argv),
  274. const_cast<char **>(Envp));
  275. else
  276. execv(PathStr.c_str(), const_cast<char **>(Argv));
  277. // If the execve() failed, we should exit. Follow Unix protocol and
  278. // return 127 if the executable was not found, and 126 otherwise.
  279. // Use _exit rather than exit so that atexit functions and static
  280. // object destructors cloned from the parent process aren't
  281. // redundantly run, and so that any data buffered in stdio buffers
  282. // cloned from the parent aren't redundantly written out.
  283. _exit(errno == ENOENT ? 127 : 126);
  284. }
  285. // Parent process: Break out of the switch to do our processing.
  286. default:
  287. break;
  288. }
  289. PI.Pid = child;
  290. PI.Process = child;
  291. return true;
  292. }
  293. namespace llvm {
  294. namespace sys {
  295. #ifndef _AIX
  296. using ::wait4;
  297. #else
  298. static pid_t (wait4)(pid_t pid, int *status, int options, struct rusage *usage);
  299. #endif
  300. } // namespace sys
  301. } // namespace llvm
  302. #ifdef _AIX
  303. #ifndef _ALL_SOURCE
  304. extern "C" pid_t (wait4)(pid_t pid, int *status, int options,
  305. struct rusage *usage);
  306. #endif
  307. pid_t (llvm::sys::wait4)(pid_t pid, int *status, int options,
  308. struct rusage *usage) {
  309. assert(pid > 0 && "Only expecting to handle actual PID values!");
  310. assert((options & ~WNOHANG) == 0 && "Expecting WNOHANG at most!");
  311. assert(usage && "Expecting usage collection!");
  312. // AIX wait4 does not work well with WNOHANG.
  313. if (!(options & WNOHANG))
  314. return ::wait4(pid, status, options, usage);
  315. // For WNOHANG, we use waitid (which supports WNOWAIT) until the child process
  316. // has terminated.
  317. siginfo_t WaitIdInfo;
  318. WaitIdInfo.si_pid = 0;
  319. int WaitIdRetVal =
  320. waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
  321. if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
  322. return WaitIdRetVal;
  323. assert(WaitIdInfo.si_pid == pid);
  324. // The child has already terminated, so a blocking wait on it is okay in the
  325. // absence of indiscriminate `wait` calls from the current process (which
  326. // would cause the call here to fail with ECHILD).
  327. return ::wait4(pid, status, options & ~WNOHANG, usage);
  328. }
  329. #endif
  330. ProcessInfo llvm::sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
  331. bool WaitUntilTerminates, std::string *ErrMsg,
  332. Optional<ProcessStatistics> *ProcStat) {
  333. struct sigaction Act, Old;
  334. assert(PI.Pid && "invalid pid to wait on, process not started?");
  335. int WaitPidOptions = 0;
  336. pid_t ChildPid = PI.Pid;
  337. if (WaitUntilTerminates) {
  338. SecondsToWait = 0;
  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. // FIXME The alarm signal may be delivered to another thread.
  348. alarm(SecondsToWait);
  349. } else if (SecondsToWait == 0)
  350. WaitPidOptions = WNOHANG;
  351. // Parent process: Wait for the child process to terminate.
  352. int status;
  353. ProcessInfo WaitResult;
  354. rusage Info;
  355. if (ProcStat)
  356. ProcStat->reset();
  357. do {
  358. WaitResult.Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &Info);
  359. } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
  360. if (WaitResult.Pid != PI.Pid) {
  361. if (WaitResult.Pid == 0) {
  362. // Non-blocking wait.
  363. return WaitResult;
  364. } else {
  365. if (SecondsToWait && errno == EINTR) {
  366. // Kill the child.
  367. kill(PI.Pid, SIGKILL);
  368. // Turn off the alarm and restore the signal handler
  369. alarm(0);
  370. sigaction(SIGALRM, &Old, nullptr);
  371. // Wait for child to die
  372. // FIXME This could grab some other child process out from another
  373. // waiting thread and then leave a zombie anyway.
  374. if (wait(&status) != ChildPid)
  375. MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
  376. else
  377. MakeErrMsg(ErrMsg, "Child timed out", 0);
  378. WaitResult.ReturnCode = -2; // Timeout detected
  379. return WaitResult;
  380. } else if (errno != EINTR) {
  381. MakeErrMsg(ErrMsg, "Error waiting for child process");
  382. WaitResult.ReturnCode = -1;
  383. return WaitResult;
  384. }
  385. }
  386. }
  387. // We exited normally without timeout, so turn off the timer.
  388. if (SecondsToWait && !WaitUntilTerminates) {
  389. alarm(0);
  390. sigaction(SIGALRM, &Old, nullptr);
  391. }
  392. if (ProcStat) {
  393. std::chrono::microseconds UserT = toDuration(Info.ru_utime);
  394. std::chrono::microseconds KernelT = toDuration(Info.ru_stime);
  395. uint64_t PeakMemory = 0;
  396. #ifndef __HAIKU__
  397. PeakMemory = static_cast<uint64_t>(Info.ru_maxrss);
  398. #endif
  399. *ProcStat = ProcessStatistics{UserT + KernelT, UserT, PeakMemory};
  400. }
  401. // Return the proper exit status. Detect error conditions
  402. // so we can return -1 for them and set ErrMsg informatively.
  403. int result = 0;
  404. if (WIFEXITED(status)) {
  405. result = WEXITSTATUS(status);
  406. WaitResult.ReturnCode = result;
  407. if (result == 127) {
  408. if (ErrMsg)
  409. *ErrMsg = llvm::sys::StrError(ENOENT);
  410. WaitResult.ReturnCode = -1;
  411. return WaitResult;
  412. }
  413. if (result == 126) {
  414. if (ErrMsg)
  415. *ErrMsg = "Program could not be executed";
  416. WaitResult.ReturnCode = -1;
  417. return WaitResult;
  418. }
  419. } else if (WIFSIGNALED(status)) {
  420. if (ErrMsg) {
  421. *ErrMsg = strsignal(WTERMSIG(status));
  422. #ifdef WCOREDUMP
  423. if (WCOREDUMP(status))
  424. *ErrMsg += " (core dumped)";
  425. #endif
  426. }
  427. // Return a special value to indicate that the process received an unhandled
  428. // signal during execution as opposed to failing to execute.
  429. WaitResult.ReturnCode = -2;
  430. }
  431. return WaitResult;
  432. }
  433. std::error_code llvm::sys::ChangeStdinMode(fs::OpenFlags Flags){
  434. if (!(Flags & fs::OF_Text))
  435. return ChangeStdinToBinary();
  436. return std::error_code();
  437. }
  438. std::error_code llvm::sys::ChangeStdoutMode(fs::OpenFlags Flags){
  439. if (!(Flags & fs::OF_Text))
  440. return ChangeStdoutToBinary();
  441. return std::error_code();
  442. }
  443. std::error_code llvm::sys::ChangeStdinToBinary() {
  444. // Do nothing, as Unix doesn't differentiate between text and binary.
  445. return std::error_code();
  446. }
  447. std::error_code llvm::sys::ChangeStdoutToBinary() {
  448. // Do nothing, as Unix doesn't differentiate between text and binary.
  449. return std::error_code();
  450. }
  451. std::error_code
  452. llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
  453. WindowsEncodingMethod Encoding /*unused*/) {
  454. std::error_code EC;
  455. llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::OF_TextWithCRLF);
  456. if (EC)
  457. return EC;
  458. OS << Contents;
  459. if (OS.has_error())
  460. return make_error_code(errc::io_error);
  461. return EC;
  462. }
  463. bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
  464. ArrayRef<StringRef> Args) {
  465. static long ArgMax = sysconf(_SC_ARG_MAX);
  466. // POSIX requires that _POSIX_ARG_MAX is 4096, which is the lowest possible
  467. // value for ARG_MAX on a POSIX compliant system.
  468. static long ArgMin = _POSIX_ARG_MAX;
  469. // This the same baseline used by xargs.
  470. long EffectiveArgMax = 128 * 1024;
  471. if (EffectiveArgMax > ArgMax)
  472. EffectiveArgMax = ArgMax;
  473. else if (EffectiveArgMax < ArgMin)
  474. EffectiveArgMax = ArgMin;
  475. // System says no practical limit.
  476. if (ArgMax == -1)
  477. return true;
  478. // Conservatively account for space required by environment variables.
  479. long HalfArgMax = EffectiveArgMax / 2;
  480. size_t ArgLength = Program.size() + 1;
  481. for (StringRef Arg : Args) {
  482. // Ensure that we do not exceed the MAX_ARG_STRLEN constant on Linux, which
  483. // does not have a constant unlike what the man pages would have you
  484. // believe. Since this limit is pretty high, perform the check
  485. // unconditionally rather than trying to be aggressive and limiting it to
  486. // Linux only.
  487. if (Arg.size() >= (32 * 4096))
  488. return false;
  489. ArgLength += Arg.size() + 1;
  490. if (ArgLength > size_t(HalfArgMax)) {
  491. return false;
  492. }
  493. }
  494. return true;
  495. }