Program.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Support/Program.h ------------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file declares the llvm::sys::Program class.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_SUPPORT_PROGRAM_H
  18. #define LLVM_SUPPORT_PROGRAM_H
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/Support/ErrorOr.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include <chrono>
  25. #include <optional>
  26. #include <system_error>
  27. namespace llvm {
  28. class BitVector;
  29. namespace sys {
  30. /// This is the OS-specific separator for PATH like environment variables:
  31. // a colon on Unix or a semicolon on Windows.
  32. #if defined(LLVM_ON_UNIX)
  33. const char EnvPathSeparator = ':';
  34. #elif defined (_WIN32)
  35. const char EnvPathSeparator = ';';
  36. #endif
  37. #if defined(_WIN32)
  38. typedef unsigned long procid_t; // Must match the type of DWORD on Windows.
  39. typedef void *process_t; // Must match the type of HANDLE on Windows.
  40. #else
  41. typedef ::pid_t procid_t;
  42. typedef procid_t process_t;
  43. #endif
  44. /// This struct encapsulates information about a process.
  45. struct ProcessInfo {
  46. enum : procid_t { InvalidPid = 0 };
  47. procid_t Pid; /// The process identifier.
  48. process_t Process; /// Platform-dependent process object.
  49. /// The return code, set after execution.
  50. int ReturnCode;
  51. ProcessInfo();
  52. };
  53. /// This struct encapsulates information about a process execution.
  54. struct ProcessStatistics {
  55. std::chrono::microseconds TotalTime;
  56. std::chrono::microseconds UserTime;
  57. uint64_t PeakMemory = 0; ///< Maximum resident set size in KiB.
  58. };
  59. /// Find the first executable file \p Name in \p Paths.
  60. ///
  61. /// This does not perform hashing as a shell would but instead stats each PATH
  62. /// entry individually so should generally be avoided. Core LLVM library
  63. /// functions and options should instead require fully specified paths.
  64. ///
  65. /// \param Name name of the executable to find. If it contains any system
  66. /// slashes, it will be returned as is.
  67. /// \param Paths optional list of paths to search for \p Name. If empty it
  68. /// will use the system PATH environment instead.
  69. ///
  70. /// \returns The fully qualified path to the first \p Name in \p Paths if it
  71. /// exists. \p Name if \p Name has slashes in it. Otherwise an error.
  72. ErrorOr<std::string>
  73. findProgramByName(StringRef Name, ArrayRef<StringRef> Paths = {});
  74. // These functions change the specified standard stream (stdin or stdout) mode
  75. // based on the Flags. They return errc::success if the specified stream was
  76. // changed. Otherwise, a platform dependent error is returned.
  77. std::error_code ChangeStdinMode(fs::OpenFlags Flags);
  78. std::error_code ChangeStdoutMode(fs::OpenFlags Flags);
  79. // These functions change the specified standard stream (stdin or stdout) to
  80. // binary mode. They return errc::success if the specified stream
  81. // was changed. Otherwise a platform dependent error is returned.
  82. std::error_code ChangeStdinToBinary();
  83. std::error_code ChangeStdoutToBinary();
  84. /// This function executes the program using the arguments provided. The
  85. /// invoked program will inherit the stdin, stdout, and stderr file
  86. /// descriptors, the environment and other configuration settings of the
  87. /// invoking program.
  88. /// This function waits for the program to finish, so should be avoided in
  89. /// library functions that aren't expected to block. Consider using
  90. /// ExecuteNoWait() instead.
  91. /// \returns an integer result code indicating the status of the program.
  92. /// A zero or positive value indicates the result code of the program.
  93. /// -1 indicates failure to execute
  94. /// -2 indicates a crash during execution or timeout
  95. int ExecuteAndWait(
  96. StringRef Program, ///< Path of the program to be executed. It is
  97. ///< presumed this is the result of the findProgramByName method.
  98. ArrayRef<StringRef> Args, ///< An array of strings that are passed to the
  99. ///< program. The first element should be the name of the program.
  100. ///< The array should **not** be terminated by an empty StringRef.
  101. std::optional<ArrayRef<StringRef>> Env =
  102. std::nullopt, ///< An optional vector of
  103. ///< strings to use for the program's environment. If not provided, the
  104. ///< current program's environment will be used. If specified, the
  105. ///< vector should **not** be terminated by an empty StringRef.
  106. ArrayRef<std::optional<StringRef>> Redirects = {}, ///<
  107. ///< An array of optional paths. Should have a size of zero or three.
  108. ///< If the array is empty, no redirections are performed.
  109. ///< Otherwise, the inferior process's stdin(0), stdout(1), and stderr(2)
  110. ///< will be redirected to the corresponding paths, if the optional path
  111. ///< is present (not \c std::nullopt).
  112. ///< When an empty path is passed in, the corresponding file descriptor
  113. ///< will be disconnected (ie, /dev/null'd) in a portable way.
  114. unsigned SecondsToWait = 0, ///< If non-zero, this specifies the amount
  115. ///< of time to wait for the child process to exit. If the time
  116. ///< expires, the child is killed and this call returns. If zero,
  117. ///< this function will wait until the child finishes or forever if
  118. ///< it doesn't.
  119. unsigned MemoryLimit = 0, ///< If non-zero, this specifies max. amount
  120. ///< of memory can be allocated by process. If memory usage will be
  121. ///< higher limit, the child is killed and this call returns. If zero
  122. ///< - no memory limit.
  123. std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
  124. ///< string instance in which error messages will be returned. If the
  125. ///< string is non-empty upon return an error occurred while invoking the
  126. ///< program.
  127. bool *ExecutionFailed = nullptr,
  128. std::optional<ProcessStatistics> *ProcStat = nullptr, ///< If non-zero,
  129. /// provides a pointer to a structure in which process execution
  130. /// statistics will be stored.
  131. BitVector *AffinityMask = nullptr ///< CPUs or processors the new
  132. /// program shall run on.
  133. );
  134. /// Similar to ExecuteAndWait, but returns immediately.
  135. /// @returns The \see ProcessInfo of the newly launched process.
  136. /// \note On Microsoft Windows systems, users will need to either call
  137. /// \see Wait until the process finished execution or win32 CloseHandle() API
  138. /// on ProcessInfo.ProcessHandle to avoid memory leaks.
  139. ProcessInfo ExecuteNoWait(StringRef Program, ArrayRef<StringRef> Args,
  140. std::optional<ArrayRef<StringRef>> Env,
  141. ArrayRef<std::optional<StringRef>> Redirects = {},
  142. unsigned MemoryLimit = 0,
  143. std::string *ErrMsg = nullptr,
  144. bool *ExecutionFailed = nullptr,
  145. BitVector *AffinityMask = nullptr);
  146. /// Return true if the given arguments fit within system-specific
  147. /// argument length limits.
  148. bool commandLineFitsWithinSystemLimits(StringRef Program,
  149. ArrayRef<StringRef> Args);
  150. /// Return true if the given arguments fit within system-specific
  151. /// argument length limits.
  152. bool commandLineFitsWithinSystemLimits(StringRef Program,
  153. ArrayRef<const char *> Args);
  154. /// File encoding options when writing contents that a non-UTF8 tool will
  155. /// read (on Windows systems). For UNIX, we always use UTF-8.
  156. enum WindowsEncodingMethod {
  157. /// UTF-8 is the LLVM native encoding, being the same as "do not perform
  158. /// encoding conversion".
  159. WEM_UTF8,
  160. WEM_CurrentCodePage,
  161. WEM_UTF16
  162. };
  163. /// Saves the UTF8-encoded \p contents string into the file \p FileName
  164. /// using a specific encoding.
  165. ///
  166. /// This write file function adds the possibility to choose which encoding
  167. /// to use when writing a text file. On Windows, this is important when
  168. /// writing files with internationalization support with an encoding that is
  169. /// different from the one used in LLVM (UTF-8). We use this when writing
  170. /// response files, since GCC tools on MinGW only understand legacy code
  171. /// pages, and VisualStudio tools only understand UTF-16.
  172. /// For UNIX, using different encodings is silently ignored, since all tools
  173. /// work well with UTF-8.
  174. /// This function assumes that you only use UTF-8 *text* data and will convert
  175. /// it to your desired encoding before writing to the file.
  176. ///
  177. /// FIXME: We use EM_CurrentCodePage to write response files for GNU tools in
  178. /// a MinGW/MinGW-w64 environment, which has serious flaws but currently is
  179. /// our best shot to make gcc/ld understand international characters. This
  180. /// should be changed as soon as binutils fix this to support UTF16 on mingw.
  181. ///
  182. /// \returns non-zero error_code if failed
  183. std::error_code
  184. writeFileWithEncoding(StringRef FileName, StringRef Contents,
  185. WindowsEncodingMethod Encoding = WEM_UTF8);
  186. /// This function waits for the process specified by \p PI to finish.
  187. /// \returns A \see ProcessInfo struct with Pid set to:
  188. /// \li The process id of the child process if the child process has changed
  189. /// state.
  190. /// \li 0 if the child process has not changed state.
  191. /// \note Users of this function should always check the ReturnCode member of
  192. /// the \see ProcessInfo returned from this function.
  193. ProcessInfo
  194. Wait(const ProcessInfo &PI, ///< The child process that should be waited on.
  195. std::optional<unsigned> SecondsToWait, ///< If std::nullopt, waits until
  196. ///< child has terminated.
  197. ///< If a value, this specifies the amount of time to wait for the child
  198. ///< process. If the time expires, and \p Polling is false, the child is
  199. ///< killed and this < function returns. If the time expires and \p
  200. ///< Polling is true, the child is resumed.
  201. ///<
  202. ///< If zero, this function will perform a non-blocking
  203. ///< wait on the child process.
  204. std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
  205. ///< string instance in which error messages will be returned. If the
  206. ///< string is non-empty upon return an error occurred while invoking the
  207. ///< program.
  208. std::optional<ProcessStatistics> *ProcStat =
  209. nullptr, ///< If non-zero, provides
  210. /// a pointer to a structure in which process execution statistics will
  211. /// be stored.
  212. bool Polling = false ///< If true, do not kill the process on timeout.
  213. );
  214. /// Print a command argument, and optionally quote it.
  215. void printArg(llvm::raw_ostream &OS, StringRef Arg, bool Quote);
  216. #if defined(_WIN32)
  217. /// Given a list of command line arguments, quote and escape them as necessary
  218. /// to build a single flat command line appropriate for calling CreateProcess
  219. /// on
  220. /// Windows.
  221. ErrorOr<std::wstring> flattenWindowsCommandLine(ArrayRef<StringRef> Args);
  222. #endif
  223. }
  224. }
  225. #endif
  226. #ifdef __GNUC__
  227. #pragma GCC diagnostic pop
  228. #endif