Program.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. //===- llvm/Support/Program.h ------------------------------------*- 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 declares the llvm::sys::Program class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_SUPPORT_PROGRAM_H
  14. #define LLVM_SUPPORT_PROGRAM_H
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/Support/ErrorOr.h"
  17. #include <system_error>
  18. namespace llvm {
  19. class StringRef;
  20. namespace sys {
  21. /// This is the OS-specific separator for PATH like environment variables:
  22. // a colon on Unix or a semicolon on Windows.
  23. #if defined(LLVM_ON_UNIX)
  24. const char EnvPathSeparator = ':';
  25. #elif defined (LLVM_ON_WIN32)
  26. const char EnvPathSeparator = ';';
  27. #endif
  28. /// @brief This struct encapsulates information about a process.
  29. struct ProcessInfo {
  30. #if defined(LLVM_ON_UNIX)
  31. typedef pid_t ProcessId;
  32. #elif defined(LLVM_ON_WIN32)
  33. typedef unsigned long ProcessId; // Must match the type of DWORD on Windows.
  34. typedef void * HANDLE; // Must match the type of HANDLE on Windows.
  35. /// The handle to the process (available on Windows only).
  36. HANDLE ProcessHandle;
  37. #else
  38. #error "ProcessInfo is not defined for this platform!"
  39. #endif
  40. /// The process identifier.
  41. ProcessId Pid;
  42. /// The return code, set after execution.
  43. int ReturnCode;
  44. ProcessInfo();
  45. };
  46. /// \brief Find the first executable file \p Name in \p Paths.
  47. ///
  48. /// This does not perform hashing as a shell would but instead stats each PATH
  49. /// entry individually so should generally be avoided. Core LLVM library
  50. /// functions and options should instead require fully specified paths.
  51. ///
  52. /// \param Name name of the executable to find. If it contains any system
  53. /// slashes, it will be returned as is.
  54. /// \param Paths optional list of paths to search for \p Name. If empty it
  55. /// will use the system PATH environment instead.
  56. ///
  57. /// \returns The fully qualified path to the first \p Name in \p Paths if it
  58. /// exists. \p Name if \p Name has slashes in it. Otherwise an error.
  59. ErrorOr<std::string>
  60. findProgramByName(StringRef Name,
  61. ArrayRef<StringRef> Paths = ArrayRef<StringRef>());
  62. // These functions change the specified standard stream (stdin or stdout) to
  63. // binary mode. They return errc::success if the specified stream
  64. // was changed. Otherwise a platform dependent error is returned.
  65. std::error_code ChangeStdinToBinary();
  66. std::error_code ChangeStdoutToBinary();
  67. /// This function executes the program using the arguments provided. The
  68. /// invoked program will inherit the stdin, stdout, and stderr file
  69. /// descriptors, the environment and other configuration settings of the
  70. /// invoking program.
  71. /// This function waits for the program to finish, so should be avoided in
  72. /// library functions that aren't expected to block. Consider using
  73. /// ExecuteNoWait() instead.
  74. /// @returns an integer result code indicating the status of the program.
  75. /// A zero or positive value indicates the result code of the program.
  76. /// -1 indicates failure to execute
  77. /// -2 indicates a crash during execution or timeout
  78. int ExecuteAndWait(
  79. StringRef Program, ///< Path of the program to be executed. It is
  80. /// presumed this is the result of the findProgramByName method.
  81. const char **args, ///< A vector of strings that are passed to the
  82. ///< program. The first element should be the name of the program.
  83. ///< The list *must* be terminated by a null char* entry.
  84. const char **env = nullptr, ///< An optional vector of strings to use for
  85. ///< the program's environment. If not provided, the current program's
  86. ///< environment will be used.
  87. const StringRef **redirects = nullptr, ///< An optional array of pointers
  88. ///< to paths. If the array is null, no redirection is done. The array
  89. ///< should have a size of at least three. The inferior process's
  90. ///< stdin(0), stdout(1), and stderr(2) will be redirected to the
  91. ///< corresponding paths.
  92. ///< When an empty path is passed in, the corresponding file
  93. ///< descriptor will be disconnected (ie, /dev/null'd) in a portable
  94. ///< way.
  95. unsigned secondsToWait = 0, ///< If non-zero, this specifies the amount
  96. ///< of time to wait for the child process to exit. If the time
  97. ///< expires, the child is killed and this call returns. If zero,
  98. ///< this function will wait until the child finishes or forever if
  99. ///< it doesn't.
  100. unsigned memoryLimit = 0, ///< If non-zero, this specifies max. amount
  101. ///< of memory can be allocated by process. If memory usage will be
  102. ///< higher limit, the child is killed and this call returns. If zero
  103. ///< - no memory limit.
  104. std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
  105. ///< string instance in which error messages will be returned. If the
  106. ///< string is non-empty upon return an error occurred while invoking the
  107. ///< program.
  108. bool *ExecutionFailed = nullptr);
  109. /// Similar to ExecuteAndWait, but returns immediately.
  110. /// @returns The \see ProcessInfo of the newly launced process.
  111. /// \note On Microsoft Windows systems, users will need to either call \see
  112. /// Wait until the process finished execution or win32 CloseHandle() API on
  113. /// ProcessInfo.ProcessHandle to avoid memory leaks.
  114. ProcessInfo
  115. ExecuteNoWait(StringRef Program, const char **args, const char **env = nullptr,
  116. const StringRef **redirects = nullptr, unsigned memoryLimit = 0,
  117. std::string *ErrMsg = nullptr, bool *ExecutionFailed = nullptr);
  118. /// Return true if the given arguments fit within system-specific
  119. /// argument length limits.
  120. bool argumentsFitWithinSystemLimits(ArrayRef<const char*> Args);
  121. /// File encoding options when writing contents that a non-UTF8 tool will
  122. /// read (on Windows systems). For UNIX, we always use UTF-8.
  123. enum WindowsEncodingMethod {
  124. /// UTF-8 is the LLVM native encoding, being the same as "do not perform
  125. /// encoding conversion".
  126. WEM_UTF8,
  127. WEM_CurrentCodePage,
  128. WEM_UTF16
  129. };
  130. /// Saves the UTF8-encoded \p contents string into the file \p FileName
  131. /// using a specific encoding.
  132. ///
  133. /// This write file function adds the possibility to choose which encoding
  134. /// to use when writing a text file. On Windows, this is important when
  135. /// writing files with internationalization support with an encoding that is
  136. /// different from the one used in LLVM (UTF-8). We use this when writing
  137. /// response files, since GCC tools on MinGW only understand legacy code
  138. /// pages, and VisualStudio tools only understand UTF-16.
  139. /// For UNIX, using different encodings is silently ignored, since all tools
  140. /// work well with UTF-8.
  141. /// This function assumes that you only use UTF-8 *text* data and will convert
  142. /// it to your desired encoding before writing to the file.
  143. ///
  144. /// FIXME: We use EM_CurrentCodePage to write response files for GNU tools in
  145. /// a MinGW/MinGW-w64 environment, which has serious flaws but currently is
  146. /// our best shot to make gcc/ld understand international characters. This
  147. /// should be changed as soon as binutils fix this to support UTF16 on mingw.
  148. ///
  149. /// \returns non-zero error_code if failed
  150. std::error_code
  151. writeFileWithEncoding(StringRef FileName, StringRef Contents,
  152. WindowsEncodingMethod Encoding = WEM_UTF8);
  153. /// This function waits for the process specified by \p PI to finish.
  154. /// \returns A \see ProcessInfo struct with Pid set to:
  155. /// \li The process id of the child process if the child process has changed
  156. /// state.
  157. /// \li 0 if the child process has not changed state.
  158. /// \note Users of this function should always check the ReturnCode member of
  159. /// the \see ProcessInfo returned from this function.
  160. ProcessInfo Wait(
  161. const ProcessInfo &PI, ///< The child process that should be waited on.
  162. unsigned SecondsToWait, ///< If non-zero, this specifies the amount of
  163. ///< time to wait for the child process to exit. If the time expires, the
  164. ///< child is killed and this function returns. If zero, this function
  165. ///< will perform a non-blocking wait on the child process.
  166. bool WaitUntilTerminates, ///< If true, ignores \p SecondsToWait and waits
  167. ///< until child has terminated.
  168. std::string *ErrMsg = nullptr ///< If non-zero, provides a pointer to a
  169. ///< string instance in which error messages will be returned. If the
  170. ///< string is non-empty upon return an error occurred while invoking the
  171. ///< program.
  172. );
  173. }
  174. }
  175. #endif