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