[Support][Program] Add findProgramByName(Name, OptionalPaths)
[oota-llvm.git] / include / llvm / Support / Program.h
1 //===- llvm/Support/Program.h ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the llvm::sys::Program class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_SUPPORT_PROGRAM_H
15 #define LLVM_SUPPORT_PROGRAM_H
16
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/Support/ErrorOr.h"
19 #include "llvm/Support/Path.h"
20 #include <system_error>
21
22 namespace llvm {
23 namespace sys {
24
25   /// This is the OS-specific separator for PATH like environment variables:
26   // a colon on Unix or a semicolon on Windows.
27 #if defined(LLVM_ON_UNIX)
28   const char EnvPathSeparator = ':';
29 #elif defined (LLVM_ON_WIN32)
30   const char EnvPathSeparator = ';';
31 #endif
32
33 /// @brief This struct encapsulates information about a process.
34 struct ProcessInfo {
35 #if defined(LLVM_ON_UNIX)
36   typedef pid_t ProcessId;
37 #elif defined(LLVM_ON_WIN32)
38   typedef unsigned long ProcessId; // Must match the type of DWORD on Windows.
39   typedef void * HANDLE; // Must match the type of HANDLE on Windows.
40   /// The handle to the process (available on Windows only).
41   HANDLE ProcessHandle;
42 #else
43 #error "ProcessInfo is not defined for this platform!"
44 #endif
45
46   /// The process identifier.
47   ProcessId Pid;
48
49   /// The return code, set after execution.
50   int ReturnCode;
51
52   ProcessInfo();
53 };
54
55   /// This function attempts to locate a program in the operating
56   /// system's file system using some pre-determined set of locations to search
57   /// (e.g. the PATH on Unix). Paths with slashes are returned unmodified.
58   ///
59   /// It does not perform hashing as a shell would but instead stats each PATH
60   /// entry individually so should generally be avoided. Core LLVM library
61   /// functions and options should instead require fully specified paths.
62   ///
63   /// @returns A string containing the path of the program or an empty string if
64   /// the program could not be found.
65   std::string FindProgramByName(const std::string& name);
66
67   /// \brief Find the first executable file \p Name in \p Paths.
68   ///
69   /// This does not perform hashing as a shell would but instead stats each PATH
70   /// entry individually so should generally be avoided. Core LLVM library
71   /// functions and options should instead require fully specified paths.
72   ///
73   /// \param Name name of the executable to find. If it contains any system
74   ///   slashes, it will be returned as is.
75   /// \param Paths optional list of paths to search for \p Name. If empty it
76   ///   will use the system PATH environment instead.
77   ///
78   /// \returns The fully qualified path to the first \p Name in \p Paths if it
79   ///   exists. \p Name if \p Name has slashes in it. Otherwise an error.
80   ErrorOr<std::string>
81   findProgramByName(StringRef Name,
82                     ArrayRef<StringRef> Paths = ArrayRef<StringRef>());
83
84   // These functions change the specified standard stream (stdin or stdout) to
85   // binary mode. They return errc::success if the specified stream
86   // was changed. Otherwise a platform dependent error is returned.
87   std::error_code ChangeStdinToBinary();
88   std::error_code ChangeStdoutToBinary();
89
90   /// This function executes the program using the arguments provided.  The
91   /// invoked program will inherit the stdin, stdout, and stderr file
92   /// descriptors, the environment and other configuration settings of the
93   /// invoking program.
94   /// This function waits for the program to finish, so should be avoided in
95   /// library functions that aren't expected to block. Consider using
96   /// ExecuteNoWait() instead.
97   /// @returns an integer result code indicating the status of the program.
98   /// A zero or positive value indicates the result code of the program.
99   /// -1 indicates failure to execute
100   /// -2 indicates a crash during execution or timeout
101   int ExecuteAndWait(
102       StringRef Program, ///< Path of the program to be executed. It is
103       /// presumed this is the result of the FindProgramByName method.
104       const char **args, ///< A vector of strings that are passed to the
105       ///< program.  The first element should be the name of the program.
106       ///< The list *must* be terminated by a null char* entry.
107       const char **env = nullptr, ///< An optional vector of strings to use for
108       ///< the program's environment. If not provided, the current program's
109       ///< environment will be used.
110       const StringRef **redirects = nullptr, ///< An optional array of pointers
111       ///< to paths. If the array is null, no redirection is done. The array
112       ///< should have a size of at least three. The inferior process's
113       ///< stdin(0), stdout(1), and stderr(2) will be redirected to the
114       ///< corresponding paths.
115       ///< When an empty path is passed in, the corresponding file
116       ///< descriptor will be disconnected (ie, /dev/null'd) in a portable
117       ///< way.
118       unsigned secondsToWait = 0, ///< If non-zero, this specifies the amount
119       ///< of time to wait for the child process to exit. If the time
120       ///< expires, the child is killed and this call returns. If zero,
121       ///< this function will wait until the child finishes or forever if
122       ///< it doesn't.
123       unsigned memoryLimit = 0, ///< If non-zero, this specifies max. amount
124       ///< of memory can be allocated by process. If memory usage will be
125       ///< higher limit, the child is killed and this call returns. If zero
126       ///< - no memory limit.
127       std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
128       ///< string instance in which error messages will be returned. If the
129       ///< string is non-empty upon return an error occurred while invoking the
130       ///< program.
131       bool *ExecutionFailed = nullptr);
132
133   /// Similar to ExecuteAndWait, but returns immediately.
134   /// @returns The \see ProcessInfo of the newly launced process.
135   /// \note On Microsoft Windows systems, users will need to either call \see
136   /// Wait until the process finished execution or win32 CloseHandle() API on
137   /// ProcessInfo.ProcessHandle to avoid memory leaks.
138   ProcessInfo
139   ExecuteNoWait(StringRef Program, const char **args, const char **env = nullptr,
140                 const StringRef **redirects = nullptr, unsigned memoryLimit = 0,
141                 std::string *ErrMsg = nullptr, bool *ExecutionFailed = nullptr);
142
143   /// Return true if the given arguments fit within system-specific
144   /// argument length limits.
145   bool argumentsFitWithinSystemLimits(ArrayRef<const char*> Args);
146
147   /// File encoding options when writing contents that a non-UTF8 tool will
148   /// read (on Windows systems). For UNIX, we always use UTF-8.
149   enum WindowsEncodingMethod {
150     /// UTF-8 is the LLVM native encoding, being the same as "do not perform
151     /// encoding conversion".
152     WEM_UTF8,
153     WEM_CurrentCodePage,
154     WEM_UTF16
155   };
156
157   /// Saves the UTF8-encoded \p contents string into the file \p FileName
158   /// using a specific encoding.
159   ///
160   /// This write file function adds the possibility to choose which encoding
161   /// to use when writing a text file. On Windows, this is important when
162   /// writing files with internationalization support with an encoding that is
163   /// different from the one used in LLVM (UTF-8). We use this when writing
164   /// response files, since GCC tools on MinGW only understand legacy code
165   /// pages, and VisualStudio tools only understand UTF-16.
166   /// For UNIX, using different encodings is silently ignored, since all tools
167   /// work well with UTF-8.
168   /// This function assumes that you only use UTF-8 *text* data and will convert
169   /// it to your desired encoding before writing to the file.
170   ///
171   /// FIXME: We use EM_CurrentCodePage to write response files for GNU tools in
172   /// a MinGW/MinGW-w64 environment, which has serious flaws but currently is
173   /// our best shot to make gcc/ld understand international characters. This
174   /// should be changed as soon as binutils fix this to support UTF16 on mingw.
175   ///
176   /// \returns non-zero error_code if failed
177   std::error_code
178   writeFileWithEncoding(StringRef FileName, StringRef Contents,
179                         WindowsEncodingMethod Encoding = WEM_UTF8);
180
181   /// This function waits for the process specified by \p PI to finish.
182   /// \returns A \see ProcessInfo struct with Pid set to:
183   /// \li The process id of the child process if the child process has changed
184   /// state.
185   /// \li 0 if the child process has not changed state.
186   /// \note Users of this function should always check the ReturnCode member of
187   /// the \see ProcessInfo returned from this function.
188   ProcessInfo Wait(
189       const ProcessInfo &PI, ///< The child process that should be waited on.
190       unsigned SecondsToWait, ///< If non-zero, this specifies the amount of
191       ///< time to wait for the child process to exit. If the time expires, the
192       ///< child is killed and this function returns. If zero, this function
193       ///< will perform a non-blocking wait on the child process.
194       bool WaitUntilTerminates, ///< If true, ignores \p SecondsToWait and waits
195       ///< until child has terminated.
196       std::string *ErrMsg = nullptr ///< If non-zero, provides a pointer to a
197       ///< string instance in which error messages will be returned. If the
198       ///< string is non-empty upon return an error occurred while invoking the
199       ///< program.
200       );
201   }
202 }
203
204 #endif