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.
50     int ReturnCode;
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.
68   ErrorOr<std::string>
69   findProgramByName(StringRef Name, ArrayRef<StringRef> Paths = {});
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.
126   ProcessInfo ExecuteNoWait(StringRef Program, ArrayRef<StringRef> Args,
127                             Optional<ArrayRef<StringRef>> Env,
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.
135   bool commandLineFitsWithinSystemLimits(StringRef Program,
136                                          ArrayRef<StringRef> Args);
137 
138   /// Return true if the given arguments fit within system-specific
139   /// argument length limits.
140   bool commandLineFitsWithinSystemLimits(StringRef Program,
141                                          ArrayRef<const char *> Args);
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.
145   enum WindowsEncodingMethod {
146     /// UTF-8 is the LLVM native encoding, being the same as "do not perform
147     /// encoding conversion".
148     WEM_UTF8,
149     WEM_CurrentCodePage,
150     WEM_UTF16
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.
184   ProcessInfo Wait(
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
209