Program.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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/BitVector.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/Config/llvm-config.h"
  24. #include "llvm/Support/ErrorOr.h"
  25. #include "llvm/Support/FileSystem.h"
  26. #include <chrono>
  27. #include <system_error>
  28. namespace llvm {
  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. Optional<ArrayRef<StringRef>> Env = None, ///< An optional vector of
  102. ///< strings to use for the program's environment. If not provided, the
  103. ///< current program's environment will be used. If specified, the
  104. ///< vector should **not** be terminated by an empty StringRef.
  105. ArrayRef<Optional<StringRef>> Redirects = {}, ///<
  106. ///< An array of optional paths. Should have a size of zero or three.
  107. ///< If the array is empty, no redirections are performed.
  108. ///< Otherwise, the inferior process's stdin(0), stdout(1), and stderr(2)
  109. ///< will be redirected to the corresponding paths, if the optional path
  110. ///< is present (not \c llvm::None).
  111. ///< When an empty path is passed in, the corresponding file descriptor
  112. ///< will be disconnected (ie, /dev/null'd) in a portable way.
  113. unsigned SecondsToWait = 0, ///< If non-zero, this specifies the amount
  114. ///< of time to wait for the child process to exit. If the time
  115. ///< expires, the child is killed and this call returns. If zero,
  116. ///< this function will wait until the child finishes or forever if
  117. ///< it doesn't.
  118. unsigned MemoryLimit = 0, ///< If non-zero, this specifies max. amount
  119. ///< of memory can be allocated by process. If memory usage will be
  120. ///< higher limit, the child is killed and this call returns. If zero
  121. ///< - no memory limit.
  122. std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
  123. ///< string instance in which error messages will be returned. If the
  124. ///< string is non-empty upon return an error occurred while invoking the
  125. ///< program.
  126. bool *ExecutionFailed = nullptr,
  127. Optional<ProcessStatistics> *ProcStat = nullptr, ///< If non-zero,
  128. /// provides a pointer to a structure in which process execution
  129. /// statistics will be stored.
  130. BitVector *AffinityMask = nullptr ///< CPUs or processors the new
  131. /// program shall run on.
  132. );
  133. /// Similar to ExecuteAndWait, but returns immediately.
  134. /// @returns The \see ProcessInfo of the newly launched process.
  135. /// \note On Microsoft Windows systems, users will need to either call
  136. /// \see Wait until the process finished execution or win32 CloseHandle() API
  137. /// on ProcessInfo.ProcessHandle to avoid memory leaks.
  138. ProcessInfo ExecuteNoWait(StringRef Program, ArrayRef<StringRef> Args,
  139. Optional<ArrayRef<StringRef>> Env,
  140. ArrayRef<Optional<StringRef>> Redirects = {},
  141. unsigned MemoryLimit = 0,
  142. std::string *ErrMsg = nullptr,
  143. bool *ExecutionFailed = nullptr,
  144. BitVector *AffinityMask = nullptr);
  145. /// Return true if the given arguments fit within system-specific
  146. /// argument length limits.
  147. bool commandLineFitsWithinSystemLimits(StringRef Program,
  148. ArrayRef<StringRef> Args);
  149. /// Return true if the given arguments fit within system-specific
  150. /// argument length limits.
  151. bool commandLineFitsWithinSystemLimits(StringRef Program,
  152. ArrayRef<const char *> Args);
  153. /// File encoding options when writing contents that a non-UTF8 tool will
  154. /// read (on Windows systems). For UNIX, we always use UTF-8.
  155. enum WindowsEncodingMethod {
  156. /// UTF-8 is the LLVM native encoding, being the same as "do not perform
  157. /// encoding conversion".
  158. WEM_UTF8,
  159. WEM_CurrentCodePage,
  160. WEM_UTF16
  161. };
  162. /// Saves the UTF8-encoded \p contents string into the file \p FileName
  163. /// using a specific encoding.
  164. ///
  165. /// This write file function adds the possibility to choose which encoding
  166. /// to use when writing a text file. On Windows, this is important when
  167. /// writing files with internationalization support with an encoding that is
  168. /// different from the one used in LLVM (UTF-8). We use this when writing
  169. /// response files, since GCC tools on MinGW only understand legacy code
  170. /// pages, and VisualStudio tools only understand UTF-16.
  171. /// For UNIX, using different encodings is silently ignored, since all tools
  172. /// work well with UTF-8.
  173. /// This function assumes that you only use UTF-8 *text* data and will convert
  174. /// it to your desired encoding before writing to the file.
  175. ///
  176. /// FIXME: We use EM_CurrentCodePage to write response files for GNU tools in
  177. /// a MinGW/MinGW-w64 environment, which has serious flaws but currently is
  178. /// our best shot to make gcc/ld understand international characters. This
  179. /// should be changed as soon as binutils fix this to support UTF16 on mingw.
  180. ///
  181. /// \returns non-zero error_code if failed
  182. std::error_code
  183. writeFileWithEncoding(StringRef FileName, StringRef Contents,
  184. WindowsEncodingMethod Encoding = WEM_UTF8);
  185. /// This function waits for the process specified by \p PI to finish.
  186. /// \returns A \see ProcessInfo struct with Pid set to:
  187. /// \li The process id of the child process if the child process has changed
  188. /// state.
  189. /// \li 0 if the child process has not changed state.
  190. /// \note Users of this function should always check the ReturnCode member of
  191. /// the \see ProcessInfo returned from this function.
  192. ProcessInfo Wait(
  193. const ProcessInfo &PI, ///< The child process that should be waited on.
  194. unsigned SecondsToWait, ///< If non-zero, this specifies the amount of
  195. ///< time to wait for the child process to exit. If the time expires, the
  196. ///< child is killed and this function returns. If zero, this function
  197. ///< will perform a non-blocking wait on the child process.
  198. bool WaitUntilTerminates, ///< If true, ignores \p SecondsToWait and waits
  199. ///< until child has terminated.
  200. std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
  201. ///< string instance in which error messages will be returned. If the
  202. ///< string is non-empty upon return an error occurred while invoking the
  203. ///< program.
  204. Optional<ProcessStatistics> *ProcStat = nullptr ///< If non-zero, provides
  205. /// a pointer to a structure in which process execution statistics will be
  206. /// stored.
  207. );
  208. /// Print a command argument, and optionally quote it.
  209. void printArg(llvm::raw_ostream &OS, StringRef Arg, bool Quote);
  210. #if defined(_WIN32)
  211. /// Given a list of command line arguments, quote and escape them as necessary
  212. /// to build a single flat command line appropriate for calling CreateProcess
  213. /// on
  214. /// Windows.
  215. ErrorOr<std::wstring> flattenWindowsCommandLine(ArrayRef<StringRef> Args);
  216. #endif
  217. }
  218. }
  219. #endif
  220. #ifdef __GNUC__
  221. #pragma GCC diagnostic pop
  222. #endif