LLVM  9.0.0svn
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/Optional.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/Support/ErrorOr.h"
21 #include <system_error>
22 
23 namespace llvm {
24 namespace sys {
25 
26  /// This is the OS-specific separator for PATH like environment variables:
27  // a colon on Unix or a semicolon on Windows.
28 #if defined(LLVM_ON_UNIX)
29  const char EnvPathSeparator = ':';
30 #elif defined (_WIN32)
31  const char EnvPathSeparator = ';';
32 #endif
33 
34 #if defined(_WIN32)
35  typedef unsigned long procid_t; // Must match the type of DWORD on Windows.
36  typedef void *process_t; // Must match the type of HANDLE on Windows.
37 #else
38  typedef pid_t procid_t;
39  typedef procid_t process_t;
40 #endif
41 
42  /// This struct encapsulates information about a process.
43  struct ProcessInfo {
44  enum : procid_t { InvalidPid = 0 };
45 
46  procid_t Pid; /// The process identifier.
47  process_t Process; /// Platform-dependent process object.
48 
49  /// The return code, set after execution.
51 
52  ProcessInfo();
53  };
54 
55  /// Find the first executable file \p Name in \p Paths.
56  ///
57  /// This does not perform hashing as a shell would but instead stats each PATH
58  /// entry individually so should generally be avoided. Core LLVM library
59  /// functions and options should instead require fully specified paths.
60  ///
61  /// \param Name name of the executable to find. If it contains any system
62  /// slashes, it will be returned as is.
63  /// \param Paths optional list of paths to search for \p Name. If empty it
64  /// will use the system PATH environment instead.
65  ///
66  /// \returns The fully qualified path to the first \p Name in \p Paths if it
67  /// exists. \p Name if \p Name has slashes in it. Otherwise an error.
70 
71  // These functions change the specified standard stream (stdin or stdout) to
72  // binary mode. They return errc::success if the specified stream
73  // was changed. Otherwise a platform dependent error is returned.
74  std::error_code ChangeStdinToBinary();
75  std::error_code ChangeStdoutToBinary();
76 
77  /// This function executes the program using the arguments provided. The
78  /// invoked program will inherit the stdin, stdout, and stderr file
79  /// descriptors, the environment and other configuration settings of the
80  /// invoking program.
81  /// This function waits for the program to finish, so should be avoided in
82  /// library functions that aren't expected to block. Consider using
83  /// ExecuteNoWait() instead.
84  /// \returns an integer result code indicating the status of the program.
85  /// A zero or positive value indicates the result code of the program.
86  /// -1 indicates failure to execute
87  /// -2 indicates a crash during execution or timeout
88  int ExecuteAndWait(
89  StringRef Program, ///< Path of the program to be executed. It is
90  ///< presumed this is the result of the findProgramByName method.
91  ArrayRef<StringRef> Args, ///< An array of strings that are passed to the
92  ///< program. The first element should be the name of the program.
93  ///< The array should **not** be terminated by an empty StringRef.
94  Optional<ArrayRef<StringRef>> Env = None, ///< An optional vector of
95  ///< strings to use for the program's environment. If not provided, the
96  ///< current program's environment will be used. If specified, the
97  ///< vector should **not** be terminated by an empty StringRef.
98  ArrayRef<Optional<StringRef>> Redirects = {}, ///<
99  ///< An array of optional paths. Should have a size of zero or three.
100  ///< If the array is empty, no redirections are performed.
101  ///< Otherwise, the inferior process's stdin(0), stdout(1), and stderr(2)
102  ///< will be redirected to the corresponding paths, if the optional path
103  ///< is present (not \c llvm::None).
104  ///< When an empty path is passed in, the corresponding file descriptor
105  ///< will be disconnected (ie, /dev/null'd) in a portable way.
106  unsigned SecondsToWait = 0, ///< If non-zero, this specifies the amount
107  ///< of time to wait for the child process to exit. If the time
108  ///< expires, the child is killed and this call returns. If zero,
109  ///< this function will wait until the child finishes or forever if
110  ///< it doesn't.
111  unsigned MemoryLimit = 0, ///< If non-zero, this specifies max. amount
112  ///< of memory can be allocated by process. If memory usage will be
113  ///< higher limit, the child is killed and this call returns. If zero
114  ///< - no memory limit.
115  std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
116  ///< string instance in which error messages will be returned. If the
117  ///< string is non-empty upon return an error occurred while invoking the
118  ///< program.
119  bool *ExecutionFailed = nullptr);
120 
121  /// Similar to ExecuteAndWait, but returns immediately.
122  /// @returns The \see ProcessInfo of the newly launced process.
123  /// \note On Microsoft Windows systems, users will need to either call
124  /// \see Wait until the process finished execution or win32 CloseHandle() API
125  /// on ProcessInfo.ProcessHandle to avoid memory leaks.
128  ArrayRef<Optional<StringRef>> Redirects = {},
129  unsigned MemoryLimit = 0,
130  std::string *ErrMsg = nullptr,
131  bool *ExecutionFailed = nullptr);
132 
133  /// Return true if the given arguments fit within system-specific
134  /// argument length limits.
136  ArrayRef<StringRef> Args);
137 
138  /// Return true if the given arguments fit within system-specific
139  /// argument length limits.
142 
143  /// File encoding options when writing contents that a non-UTF8 tool will
144  /// read (on Windows systems). For UNIX, we always use UTF-8.
146  /// UTF-8 is the LLVM native encoding, being the same as "do not perform
147  /// encoding conversion".
151  };
152 
153  /// Saves the UTF8-encoded \p contents string into the file \p FileName
154  /// using a specific encoding.
155  ///
156  /// This write file function adds the possibility to choose which encoding
157  /// to use when writing a text file. On Windows, this is important when
158  /// writing files with internationalization support with an encoding that is
159  /// different from the one used in LLVM (UTF-8). We use this when writing
160  /// response files, since GCC tools on MinGW only understand legacy code
161  /// pages, and VisualStudio tools only understand UTF-16.
162  /// For UNIX, using different encodings is silently ignored, since all tools
163  /// work well with UTF-8.
164  /// This function assumes that you only use UTF-8 *text* data and will convert
165  /// it to your desired encoding before writing to the file.
166  ///
167  /// FIXME: We use EM_CurrentCodePage to write response files for GNU tools in
168  /// a MinGW/MinGW-w64 environment, which has serious flaws but currently is
169  /// our best shot to make gcc/ld understand international characters. This
170  /// should be changed as soon as binutils fix this to support UTF16 on mingw.
171  ///
172  /// \returns non-zero error_code if failed
173  std::error_code
174  writeFileWithEncoding(StringRef FileName, StringRef Contents,
175  WindowsEncodingMethod Encoding = WEM_UTF8);
176 
177  /// This function waits for the process specified by \p PI to finish.
178  /// \returns A \see ProcessInfo struct with Pid set to:
179  /// \li The process id of the child process if the child process has changed
180  /// state.
181  /// \li 0 if the child process has not changed state.
182  /// \note Users of this function should always check the ReturnCode member of
183  /// the \see ProcessInfo returned from this function.
185  const ProcessInfo &PI, ///< The child process that should be waited on.
186  unsigned SecondsToWait, ///< If non-zero, this specifies the amount of
187  ///< time to wait for the child process to exit. If the time expires, the
188  ///< child is killed and this function returns. If zero, this function
189  ///< will perform a non-blocking wait on the child process.
190  bool WaitUntilTerminates, ///< If true, ignores \p SecondsToWait and waits
191  ///< until child has terminated.
192  std::string *ErrMsg = nullptr ///< If non-zero, provides a pointer to a
193  ///< string instance in which error messages will be returned. If the
194  ///< string is non-empty upon return an error occurred while invoking the
195  ///< program.
196  );
197 
198 #if defined(_WIN32)
199  /// Given a list of command line arguments, quote and escape them as necessary
200  /// to build a single flat command line appropriate for calling CreateProcess
201  /// on
202  /// Windows.
203  std::string flattenWindowsCommandLine(ArrayRef<StringRef> Args);
204 #endif
205  }
206 }
207 
208 #endif
Represents either an error or a value T.
Definition: ErrorOr.h:56
This class represents lattice values for constants.
Definition: AllocatorList.h:23
ProcessInfo ExecuteNoWait(StringRef Program, ArrayRef< StringRef > Args, Optional< ArrayRef< StringRef >> Env, ArrayRef< Optional< StringRef >> Redirects={}, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr)
Similar to ExecuteAndWait, but returns immediately.
Definition: Program.cpp:51
std::error_code ChangeStdoutToBinary()
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
UTF-8 is the LLVM native encoding, being the same as "do not perform encoding conversion"...
Definition: Program.h:148
int ExecuteAndWait(StringRef Program, ArrayRef< StringRef > Args, Optional< ArrayRef< StringRef >> Env=None, ArrayRef< Optional< StringRef >> Redirects={}, unsigned SecondsToWait=0, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr)
This function executes the program using the arguments provided.
Definition: Program.cpp:30
const char EnvPathSeparator
This is the OS-specific separator for PATH like environment variables:
Definition: Program.h:29
procid_t process_t
Definition: Program.h:39
amdgpu Simplify well known AMD library false Value Value const Twine & Name
process_t Process
The process identifier.
Definition: Program.h:47
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
pid_t procid_t
Definition: Program.h:38
bool commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef< StringRef > Args)
Return true if the given arguments fit within system-specific argument length limits.
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.
WindowsEncodingMethod
File encoding options when writing contents that a non-UTF8 tool will read (on Windows systems)...
Definition: Program.h:145
int ReturnCode
Platform-dependent process object.
Definition: Program.h:50
std::error_code ChangeStdinToBinary()
This struct encapsulates information about a process.
Definition: Program.h:43
Provides ErrorOr<T> smart pointer.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
ProcessInfo Wait(const ProcessInfo &PI, unsigned SecondsToWait, bool WaitUntilTerminates, std::string *ErrMsg=nullptr)
This function waits for the process specified by PI to finish.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.