blob: bfd271958788267c41310d1bf23062af6b4ece5a [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/Support/Program.h ------------------------------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
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"
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020017#include "llvm/ADT/BitVector.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010018#include "llvm/ADT/Optional.h"
19#include "llvm/ADT/StringRef.h"
Andrew Scullcdfcccc2018-10-05 20:58:37 +010020#include "llvm/Config/llvm-config.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010021#include "llvm/Support/ErrorOr.h"
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020022#include <chrono>
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010023#include <system_error>
24
25namespace llvm {
26namespace sys {
27
28 /// This is the OS-specific separator for PATH like environment variables:
29 // a colon on Unix or a semicolon on Windows.
30#if defined(LLVM_ON_UNIX)
31 const char EnvPathSeparator = ':';
Andrew Scullcdfcccc2018-10-05 20:58:37 +010032#elif defined (_WIN32)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010033 const char EnvPathSeparator = ';';
34#endif
35
Andrew Scullcdfcccc2018-10-05 20:58:37 +010036#if defined(_WIN32)
37 typedef unsigned long procid_t; // Must match the type of DWORD on Windows.
38 typedef void *process_t; // Must match the type of HANDLE on Windows.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010039#else
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020040 typedef ::pid_t procid_t;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010041 typedef procid_t process_t;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010042#endif
43
Andrew Scullcdfcccc2018-10-05 20:58:37 +010044 /// This struct encapsulates information about a process.
45 struct ProcessInfo {
46 enum : procid_t { InvalidPid = 0 };
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010047
Andrew Scullcdfcccc2018-10-05 20:58:37 +010048 procid_t Pid; /// The process identifier.
49 process_t Process; /// Platform-dependent process object.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010050
Andrew Scullcdfcccc2018-10-05 20:58:37 +010051 /// The return code, set after execution.
52 int ReturnCode;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010053
Andrew Scullcdfcccc2018-10-05 20:58:37 +010054 ProcessInfo();
55 };
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010056
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020057 /// This struct encapsulates information about a process execution.
58 struct ProcessStatistics {
59 std::chrono::microseconds TotalTime;
60 std::chrono::microseconds UserTime;
61 uint64_t PeakMemory = 0; ///< Maximum resident set size in KiB.
62 };
63
Andrew Scullcdfcccc2018-10-05 20:58:37 +010064 /// Find the first executable file \p Name in \p Paths.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010065 ///
66 /// This does not perform hashing as a shell would but instead stats each PATH
67 /// entry individually so should generally be avoided. Core LLVM library
68 /// functions and options should instead require fully specified paths.
69 ///
70 /// \param Name name of the executable to find. If it contains any system
71 /// slashes, it will be returned as is.
72 /// \param Paths optional list of paths to search for \p Name. If empty it
73 /// will use the system PATH environment instead.
74 ///
75 /// \returns The fully qualified path to the first \p Name in \p Paths if it
76 /// exists. \p Name if \p Name has slashes in it. Otherwise an error.
77 ErrorOr<std::string>
78 findProgramByName(StringRef Name, ArrayRef<StringRef> Paths = {});
79
80 // These functions change the specified standard stream (stdin or stdout) to
81 // binary mode. They return errc::success if the specified stream
82 // was changed. Otherwise a platform dependent error is returned.
83 std::error_code ChangeStdinToBinary();
84 std::error_code ChangeStdoutToBinary();
85
86 /// This function executes the program using the arguments provided. The
87 /// invoked program will inherit the stdin, stdout, and stderr file
88 /// descriptors, the environment and other configuration settings of the
89 /// invoking program.
90 /// This function waits for the program to finish, so should be avoided in
91 /// library functions that aren't expected to block. Consider using
92 /// ExecuteNoWait() instead.
93 /// \returns an integer result code indicating the status of the program.
94 /// A zero or positive value indicates the result code of the program.
95 /// -1 indicates failure to execute
96 /// -2 indicates a crash during execution or timeout
97 int ExecuteAndWait(
98 StringRef Program, ///< Path of the program to be executed. It is
99 ///< presumed this is the result of the findProgramByName method.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100100 ArrayRef<StringRef> Args, ///< An array of strings that are passed to the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100101 ///< program. The first element should be the name of the program.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100102 ///< The array should **not** be terminated by an empty StringRef.
103 Optional<ArrayRef<StringRef>> Env = None, ///< An optional vector of
104 ///< strings to use for the program's environment. If not provided, the
105 ///< current program's environment will be used. If specified, the
106 ///< vector should **not** be terminated by an empty StringRef.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100107 ArrayRef<Optional<StringRef>> Redirects = {}, ///<
108 ///< An array of optional paths. Should have a size of zero or three.
109 ///< If the array is empty, no redirections are performed.
110 ///< Otherwise, the inferior process's stdin(0), stdout(1), and stderr(2)
111 ///< will be redirected to the corresponding paths, if the optional path
112 ///< is present (not \c llvm::None).
113 ///< When an empty path is passed in, the corresponding file descriptor
114 ///< will be disconnected (ie, /dev/null'd) in a portable way.
115 unsigned SecondsToWait = 0, ///< If non-zero, this specifies the amount
116 ///< of time to wait for the child process to exit. If the time
117 ///< expires, the child is killed and this call returns. If zero,
118 ///< this function will wait until the child finishes or forever if
119 ///< it doesn't.
120 unsigned MemoryLimit = 0, ///< If non-zero, this specifies max. amount
121 ///< of memory can be allocated by process. If memory usage will be
122 ///< higher limit, the child is killed and this call returns. If zero
123 ///< - no memory limit.
124 std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
125 ///< string instance in which error messages will be returned. If the
126 ///< string is non-empty upon return an error occurred while invoking the
127 ///< program.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200128 bool *ExecutionFailed = nullptr,
129 Optional<ProcessStatistics> *ProcStat = nullptr, ///< If non-zero,
130 /// provides a pointer to a structure in which process execution
131 /// statistics will be stored.
132 BitVector *AffinityMask = nullptr ///< CPUs or processors the new
133 /// program shall run on.
134 );
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100135
136 /// Similar to ExecuteAndWait, but returns immediately.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200137 /// @returns The \see ProcessInfo of the newly launched process.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100138 /// \note On Microsoft Windows systems, users will need to either call
139 /// \see Wait until the process finished execution or win32 CloseHandle() API
140 /// on ProcessInfo.ProcessHandle to avoid memory leaks.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100141 ProcessInfo ExecuteNoWait(StringRef Program, ArrayRef<StringRef> Args,
142 Optional<ArrayRef<StringRef>> Env,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100143 ArrayRef<Optional<StringRef>> Redirects = {},
144 unsigned MemoryLimit = 0,
145 std::string *ErrMsg = nullptr,
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200146 bool *ExecutionFailed = nullptr,
147 BitVector *AffinityMask = nullptr);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100148
149 /// Return true if the given arguments fit within system-specific
150 /// argument length limits.
151 bool commandLineFitsWithinSystemLimits(StringRef Program,
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100152 ArrayRef<StringRef> Args);
153
154 /// Return true if the given arguments fit within system-specific
155 /// argument length limits.
156 bool commandLineFitsWithinSystemLimits(StringRef Program,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100157 ArrayRef<const char *> Args);
158
159 /// File encoding options when writing contents that a non-UTF8 tool will
160 /// read (on Windows systems). For UNIX, we always use UTF-8.
161 enum WindowsEncodingMethod {
162 /// UTF-8 is the LLVM native encoding, being the same as "do not perform
163 /// encoding conversion".
164 WEM_UTF8,
165 WEM_CurrentCodePage,
166 WEM_UTF16
167 };
168
169 /// Saves the UTF8-encoded \p contents string into the file \p FileName
170 /// using a specific encoding.
171 ///
172 /// This write file function adds the possibility to choose which encoding
173 /// to use when writing a text file. On Windows, this is important when
174 /// writing files with internationalization support with an encoding that is
175 /// different from the one used in LLVM (UTF-8). We use this when writing
176 /// response files, since GCC tools on MinGW only understand legacy code
177 /// pages, and VisualStudio tools only understand UTF-16.
178 /// For UNIX, using different encodings is silently ignored, since all tools
179 /// work well with UTF-8.
180 /// This function assumes that you only use UTF-8 *text* data and will convert
181 /// it to your desired encoding before writing to the file.
182 ///
183 /// FIXME: We use EM_CurrentCodePage to write response files for GNU tools in
184 /// a MinGW/MinGW-w64 environment, which has serious flaws but currently is
185 /// our best shot to make gcc/ld understand international characters. This
186 /// should be changed as soon as binutils fix this to support UTF16 on mingw.
187 ///
188 /// \returns non-zero error_code if failed
189 std::error_code
190 writeFileWithEncoding(StringRef FileName, StringRef Contents,
191 WindowsEncodingMethod Encoding = WEM_UTF8);
192
193 /// This function waits for the process specified by \p PI to finish.
194 /// \returns A \see ProcessInfo struct with Pid set to:
195 /// \li The process id of the child process if the child process has changed
196 /// state.
197 /// \li 0 if the child process has not changed state.
198 /// \note Users of this function should always check the ReturnCode member of
199 /// the \see ProcessInfo returned from this function.
200 ProcessInfo Wait(
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200201 const ProcessInfo &PI, ///< The child process that should be waited on.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100202 unsigned SecondsToWait, ///< If non-zero, this specifies the amount of
203 ///< time to wait for the child process to exit. If the time expires, the
204 ///< child is killed and this function returns. If zero, this function
205 ///< will perform a non-blocking wait on the child process.
206 bool WaitUntilTerminates, ///< If true, ignores \p SecondsToWait and waits
207 ///< until child has terminated.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200208 std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100209 ///< string instance in which error messages will be returned. If the
210 ///< string is non-empty upon return an error occurred while invoking the
211 ///< program.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200212 Optional<ProcessStatistics> *ProcStat = nullptr ///< If non-zero, provides
213 /// a pointer to a structure in which process execution statistics will be
214 /// stored.
215 );
216
217 /// Print a command argument, and optionally quote it.
218 void printArg(llvm::raw_ostream &OS, StringRef Arg, bool Quote);
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100219
220#if defined(_WIN32)
221 /// Given a list of command line arguments, quote and escape them as necessary
222 /// to build a single flat command line appropriate for calling CreateProcess
223 /// on
224 /// Windows.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200225 ErrorOr<std::wstring> flattenWindowsCommandLine(ArrayRef<StringRef> Args);
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100226#endif
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100227 }
228}
229
230#endif