1 //===- llvm/Support/Program.h ------------------------------------*- 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 declares the llvm::sys::Program class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_SUPPORT_PROGRAM_H 14 #define LLVM_SUPPORT_PROGRAM_H 15 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/Config/llvm-config.h" 20 #include "llvm/Support/ErrorOr.h" 21 #include <chrono> 22 #include <system_error> 23 24 namespace llvm { 25 namespace sys { 26 27 /// This is the OS-specific separator for PATH like environment variables: 28 // a colon on Unix or a semicolon on Windows. 29 #if defined(LLVM_ON_UNIX) 30 const char EnvPathSeparator = ':'; 31 #elif defined (_WIN32) 32 const char EnvPathSeparator = ';'; 33 #endif 34 35 #if defined(_WIN32) 36 typedef unsigned long procid_t; // Must match the type of DWORD on Windows. 37 typedef void *process_t; // Must match the type of HANDLE on Windows. 38 #else 39 typedef pid_t procid_t; 40 typedef procid_t process_t; 41 #endif 42 43 /// This struct encapsulates information about a process. 44 struct ProcessInfo { 45 enum : procid_t { InvalidPid = 0 }; 46 47 procid_t Pid; /// The process identifier. 48 process_t Process; /// Platform-dependent process object. 49 50 /// The return code, set after execution. 51 int ReturnCode; 52 53 ProcessInfo(); 54 }; 55 56 /// This struct encapsulates information about a process execution. 57 struct ProcessStatistics { 58 std::chrono::microseconds TotalTime; 59 std::chrono::microseconds UserTime; 60 uint64_t PeakMemory = 0; ///< Maximum resident set size in KiB. 61 }; 62 63 /// Find the first executable file \p Name in \p Paths. 64 /// 65 /// This does not perform hashing as a shell would but instead stats each PATH 66 /// entry individually so should generally be avoided. Core LLVM library 67 /// functions and options should instead require fully specified paths. 68 /// 69 /// \param Name name of the executable to find. If it contains any system 70 /// slashes, it will be returned as is. 71 /// \param Paths optional list of paths to search for \p Name. If empty it 72 /// will use the system PATH environment instead. 73 /// 74 /// \returns The fully qualified path to the first \p Name in \p Paths if it 75 /// exists. \p Name if \p Name has slashes in it. Otherwise an error. 76 ErrorOr<std::string> 77 findProgramByName(StringRef Name, ArrayRef<StringRef> Paths = {}); 78 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 85 /// This function executes the program using the arguments provided. The 86 /// invoked program will inherit the stdin, stdout, and stderr file 87 /// descriptors, the environment and other configuration settings of the 88 /// invoking program. 89 /// This function waits for the program to finish, so should be avoided in 90 /// library functions that aren't expected to block. Consider using 91 /// ExecuteNoWait() instead. 92 /// \returns an integer result code indicating the status of the program. 93 /// A zero or positive value indicates the result code of the program. 94 /// -1 indicates failure to execute 95 /// -2 indicates a crash during execution or timeout 96 int ExecuteAndWait( 97 StringRef Program, ///< Path of the program to be executed. It is 98 ///< presumed this is the result of the findProgramByName method. 99 ArrayRef<StringRef> Args, ///< An array of strings that are passed to the 100 ///< program. The first element should be the name of the program. 101 ///< The array should **not** be terminated by an empty StringRef. 102 Optional<ArrayRef<StringRef>> Env = None, ///< 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<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 llvm::None). 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 Optional<ProcessStatistics> *ProcStat = nullptr ///< If non-zero, provides 129 /// a pointer to a structure in which process execution statistics will be 130 /// stored. 131 ); 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 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 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 155 /// File encoding options when writing contents that a non-UTF8 tool will 156 /// read (on Windows systems). For UNIX, we always use UTF-8. 157 enum WindowsEncodingMethod { 158 /// UTF-8 is the LLVM native encoding, being the same as "do not perform 159 /// encoding conversion". 160 WEM_UTF8, 161 WEM_CurrentCodePage, 162 WEM_UTF16 163 }; 164 165 /// Saves the UTF8-encoded \p contents string into the file \p FileName 166 /// using a specific encoding. 167 /// 168 /// This write file function adds the possibility to choose which encoding 169 /// to use when writing a text file. On Windows, this is important when 170 /// writing files with internationalization support with an encoding that is 171 /// different from the one used in LLVM (UTF-8). We use this when writing 172 /// response files, since GCC tools on MinGW only understand legacy code 173 /// pages, and VisualStudio tools only understand UTF-16. 174 /// For UNIX, using different encodings is silently ignored, since all tools 175 /// work well with UTF-8. 176 /// This function assumes that you only use UTF-8 *text* data and will convert 177 /// it to your desired encoding before writing to the file. 178 /// 179 /// FIXME: We use EM_CurrentCodePage to write response files for GNU tools in 180 /// a MinGW/MinGW-w64 environment, which has serious flaws but currently is 181 /// our best shot to make gcc/ld understand international characters. This 182 /// should be changed as soon as binutils fix this to support UTF16 on mingw. 183 /// 184 /// \returns non-zero error_code if failed 185 std::error_code 186 writeFileWithEncoding(StringRef FileName, StringRef Contents, 187 WindowsEncodingMethod Encoding = WEM_UTF8); 188 189 /// This function waits for the process specified by \p PI to finish. 190 /// \returns A \see ProcessInfo struct with Pid set to: 191 /// \li The process id of the child process if the child process has changed 192 /// state. 193 /// \li 0 if the child process has not changed state. 194 /// \note Users of this function should always check the ReturnCode member of 195 /// the \see ProcessInfo returned from this function. 196 ProcessInfo Wait( 197 const ProcessInfo &PI, ///< The child process that should be waited on. 198 unsigned SecondsToWait, ///< If non-zero, this specifies the amount of 199 ///< time to wait for the child process to exit. If the time expires, the 200 ///< child is killed and this function returns. If zero, this function 201 ///< will perform a non-blocking wait on the child process. 202 bool WaitUntilTerminates, ///< If true, ignores \p SecondsToWait and waits 203 ///< until child has terminated. 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 Optional<ProcessStatistics> *ProcStat = nullptr ///< If non-zero, provides 209 /// a pointer to a structure in which process execution statistics will be 210 /// stored. 211 ); 212 213 /// Print a command argument, and optionally quote it. 214 void printArg(llvm::raw_ostream &OS, StringRef Arg, bool Quote); 215 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 std::string flattenWindowsCommandLine(ArrayRef<StringRef> Args); 222 #endif 223 } 224 } 225 226 #endif 227