OSDN Git Service

Revert "Resubmit "[Support] Expose flattenWindowsCommandLine.""
[android-x86/external-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/ADT/Optional.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Config/llvm-config.h"
21 #include "llvm/Support/ErrorOr.h"
22 #include <system_error>
23
24 namespace llvm {
25 namespace sys {
26
27   /// This is the OS-specific separator for PATH like environment variables:
28   // a colon on Unix or a semicolon on Windows.
29 #if defined(LLVM_ON_UNIX)
30   const char EnvPathSeparator = ':';
31 #elif defined (_WIN32)
32   const char EnvPathSeparator = ';';
33 #endif
34
35 #if defined(_WIN32)
36   typedef unsigned long procid_t; // Must match the type of DWORD on Windows.
37   typedef void *process_t;        // Must match the type of HANDLE on Windows.
38 #else
39   typedef pid_t procid_t;
40   typedef procid_t process_t;
41 #endif
42
43   /// This struct encapsulates information about a process.
44   struct ProcessInfo {
45     enum : procid_t { InvalidPid = 0 };
46
47     procid_t Pid;      /// The process identifier.
48     process_t Process; /// Platform-dependent process object.
49
50     /// The return code, set after execution.
51     int ReturnCode;
52
53     ProcessInfo();
54   };
55
56   /// Find the first executable file \p Name in \p Paths.
57   ///
58   /// This does not perform hashing as a shell would but instead stats each PATH
59   /// entry individually so should generally be avoided. Core LLVM library
60   /// functions and options should instead require fully specified paths.
61   ///
62   /// \param Name name of the executable to find. If it contains any system
63   ///   slashes, it will be returned as is.
64   /// \param Paths optional list of paths to search for \p Name. If empty it
65   ///   will use the system PATH environment instead.
66   ///
67   /// \returns The fully qualified path to the first \p Name in \p Paths if it
68   ///   exists. \p Name if \p Name has slashes in it. Otherwise an error.
69   ErrorOr<std::string>
70   findProgramByName(StringRef Name, ArrayRef<StringRef> Paths = {});
71
72   // These functions change the specified standard stream (stdin or stdout) to
73   // binary mode. They return errc::success if the specified stream
74   // was changed. Otherwise a platform dependent error is returned.
75   std::error_code ChangeStdinToBinary();
76   std::error_code ChangeStdoutToBinary();
77
78   /// This function executes the program using the arguments provided.  The
79   /// invoked program will inherit the stdin, stdout, and stderr file
80   /// descriptors, the environment and other configuration settings of the
81   /// invoking program.
82   /// This function waits for the program to finish, so should be avoided in
83   /// library functions that aren't expected to block. Consider using
84   /// ExecuteNoWait() instead.
85   /// \returns an integer result code indicating the status of the program.
86   /// A zero or positive value indicates the result code of the program.
87   /// -1 indicates failure to execute
88   /// -2 indicates a crash during execution or timeout
89   int ExecuteAndWait(
90       StringRef Program, ///< Path of the program to be executed. It is
91       ///< presumed this is the result of the findProgramByName method.
92       const char **Args, ///< A vector of strings that are passed to the
93       ///< program.  The first element should be the name of the program.
94       ///< The list *must* be terminated by a null char* entry.
95       const char **Env = nullptr, ///< An optional vector of strings to use for
96       ///< the program's environment. If not provided, the current program's
97       ///< environment will be used.
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, const char **Args,
127                             const char **Env = nullptr,
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<const char *> Args);
137
138   /// File encoding options when writing contents that a non-UTF8 tool will
139   /// read (on Windows systems). For UNIX, we always use UTF-8.
140   enum WindowsEncodingMethod {
141     /// UTF-8 is the LLVM native encoding, being the same as "do not perform
142     /// encoding conversion".
143     WEM_UTF8,
144     WEM_CurrentCodePage,
145     WEM_UTF16
146   };
147
148   /// Saves the UTF8-encoded \p contents string into the file \p FileName
149   /// using a specific encoding.
150   ///
151   /// This write file function adds the possibility to choose which encoding
152   /// to use when writing a text file. On Windows, this is important when
153   /// writing files with internationalization support with an encoding that is
154   /// different from the one used in LLVM (UTF-8). We use this when writing
155   /// response files, since GCC tools on MinGW only understand legacy code
156   /// pages, and VisualStudio tools only understand UTF-16.
157   /// For UNIX, using different encodings is silently ignored, since all tools
158   /// work well with UTF-8.
159   /// This function assumes that you only use UTF-8 *text* data and will convert
160   /// it to your desired encoding before writing to the file.
161   ///
162   /// FIXME: We use EM_CurrentCodePage to write response files for GNU tools in
163   /// a MinGW/MinGW-w64 environment, which has serious flaws but currently is
164   /// our best shot to make gcc/ld understand international characters. This
165   /// should be changed as soon as binutils fix this to support UTF16 on mingw.
166   ///
167   /// \returns non-zero error_code if failed
168   std::error_code
169   writeFileWithEncoding(StringRef FileName, StringRef Contents,
170                         WindowsEncodingMethod Encoding = WEM_UTF8);
171
172   /// This function waits for the process specified by \p PI to finish.
173   /// \returns A \see ProcessInfo struct with Pid set to:
174   /// \li The process id of the child process if the child process has changed
175   /// state.
176   /// \li 0 if the child process has not changed state.
177   /// \note Users of this function should always check the ReturnCode member of
178   /// the \see ProcessInfo returned from this function.
179   ProcessInfo Wait(
180       const ProcessInfo &PI, ///< The child process that should be waited on.
181       unsigned SecondsToWait, ///< If non-zero, this specifies the amount of
182       ///< time to wait for the child process to exit. If the time expires, the
183       ///< child is killed and this function returns. If zero, this function
184       ///< will perform a non-blocking wait on the child process.
185       bool WaitUntilTerminates, ///< If true, ignores \p SecondsToWait and waits
186       ///< until child has terminated.
187       std::string *ErrMsg = nullptr ///< If non-zero, provides a pointer to a
188       ///< string instance in which error messages will be returned. If the
189       ///< string is non-empty upon return an error occurred while invoking the
190       ///< program.
191       );
192   }
193 }
194
195 #endif