Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:33

0001 //===- llvm/Support/Program.h ------------------------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file declares the llvm::sys::Program class.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_SUPPORT_PROGRAM_H
0014 #define LLVM_SUPPORT_PROGRAM_H
0015 
0016 #include "llvm/ADT/ArrayRef.h"
0017 #include "llvm/ADT/StringRef.h"
0018 #include "llvm/Config/llvm-config.h"
0019 #include "llvm/Support/ErrorOr.h"
0020 #include "llvm/Support/FileSystem.h"
0021 #include <chrono>
0022 #include <optional>
0023 #include <system_error>
0024 
0025 namespace llvm {
0026 class BitVector;
0027 namespace sys {
0028 
0029   /// This is the OS-specific separator for PATH like environment variables:
0030   // a colon on Unix or a semicolon on Windows.
0031 #if defined(LLVM_ON_UNIX)
0032   const char EnvPathSeparator = ':';
0033 #elif defined (_WIN32)
0034   const char EnvPathSeparator = ';';
0035 #endif
0036 
0037 #if defined(_WIN32)
0038   typedef unsigned long procid_t; // Must match the type of DWORD on Windows.
0039   typedef void *process_t;        // Must match the type of HANDLE on Windows.
0040 #else
0041   typedef ::pid_t procid_t;
0042   typedef procid_t process_t;
0043 #endif
0044 
0045   /// This struct encapsulates information about a process.
0046   struct ProcessInfo {
0047     enum : procid_t { InvalidPid = 0 };
0048 
0049     procid_t Pid;      /// The process identifier.
0050     process_t Process; /// Platform-dependent process object.
0051 
0052     /// The return code, set after execution.
0053     int ReturnCode;
0054 
0055     ProcessInfo();
0056   };
0057 
0058   /// This struct encapsulates information about a process execution.
0059   struct ProcessStatistics {
0060     std::chrono::microseconds TotalTime;
0061     std::chrono::microseconds UserTime;
0062     uint64_t PeakMemory = 0; ///< Maximum resident set size in KiB.
0063   };
0064 
0065   /// Find the first executable file \p Name in \p Paths.
0066   ///
0067   /// This does not perform hashing as a shell would but instead stats each PATH
0068   /// entry individually so should generally be avoided. Core LLVM library
0069   /// functions and options should instead require fully specified paths.
0070   ///
0071   /// \param Name name of the executable to find. If it contains any system
0072   ///   slashes, it will be returned as is.
0073   /// \param Paths optional list of paths to search for \p Name. If empty it
0074   ///   will use the system PATH environment instead.
0075   ///
0076   /// \returns The fully qualified path to the first \p Name in \p Paths if it
0077   ///   exists. \p Name if \p Name has slashes in it. Otherwise an error.
0078   ErrorOr<std::string>
0079   findProgramByName(StringRef Name, ArrayRef<StringRef> Paths = {});
0080 
0081   // These functions change the specified standard stream (stdin or stdout) mode
0082   // based on the Flags. They return errc::success if the specified stream was
0083   // changed. Otherwise, a platform dependent error is returned.
0084   std::error_code ChangeStdinMode(fs::OpenFlags Flags);
0085   std::error_code ChangeStdoutMode(fs::OpenFlags Flags);
0086 
0087   // These functions change the specified standard stream (stdin or stdout) to
0088   // binary mode. They return errc::success if the specified stream
0089   // was changed. Otherwise a platform dependent error is returned.
0090   std::error_code ChangeStdinToBinary();
0091   std::error_code ChangeStdoutToBinary();
0092 
0093   /// This function executes the program using the arguments provided.  The
0094   /// invoked program will inherit the stdin, stdout, and stderr file
0095   /// descriptors, the environment and other configuration settings of the
0096   /// invoking program.
0097   /// This function waits for the program to finish, so should be avoided in
0098   /// library functions that aren't expected to block. Consider using
0099   /// ExecuteNoWait() instead.
0100   /// \returns an integer result code indicating the status of the program.
0101   /// A zero or positive value indicates the result code of the program.
0102   /// -1 indicates failure to execute
0103   /// -2 indicates a crash during execution or timeout
0104   int ExecuteAndWait(
0105       StringRef Program, ///< Path of the program to be executed. It is
0106       ///< presumed this is the result of the findProgramByName method.
0107       ArrayRef<StringRef> Args, ///< An array of strings that are passed to the
0108       ///< program.  The first element should be the name of the program.
0109       ///< The array should **not** be terminated by an empty StringRef.
0110       std::optional<ArrayRef<StringRef>> Env =
0111           std::nullopt, ///< An optional vector of
0112       ///< strings to use for the program's environment. If not provided, the
0113       ///< current program's environment will be used.  If specified, the
0114       ///< vector should **not** be terminated by an empty StringRef.
0115       ArrayRef<std::optional<StringRef>> Redirects = {}, ///<
0116       ///< An array of optional paths. Should have a size of zero or three.
0117       ///< If the array is empty, no redirections are performed.
0118       ///< Otherwise, the inferior process's stdin(0), stdout(1), and stderr(2)
0119       ///< will be redirected to the corresponding paths, if the optional path
0120       ///< is present (not \c std::nullopt).
0121       ///< When an empty path is passed in, the corresponding file descriptor
0122       ///< will be disconnected (ie, /dev/null'd) in a portable way.
0123       unsigned SecondsToWait = 0, ///< If non-zero, this specifies the amount
0124       ///< of time to wait for the child process to exit. If the time
0125       ///< expires, the child is killed and this call returns. If zero,
0126       ///< this function will wait until the child finishes or forever if
0127       ///< it doesn't.
0128       unsigned MemoryLimit = 0, ///< If non-zero, this specifies max. amount
0129       ///< of memory can be allocated by process. If memory usage will be
0130       ///< higher limit, the child is killed and this call returns. If zero
0131       ///< - no memory limit.
0132       std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
0133       ///< string instance in which error messages will be returned. If the
0134       ///< string is non-empty upon return an error occurred while invoking the
0135       ///< program.
0136       bool *ExecutionFailed = nullptr,
0137       std::optional<ProcessStatistics> *ProcStat = nullptr, ///< If non-zero,
0138       /// provides a pointer to a structure in which process execution
0139       /// statistics will be stored.
0140       BitVector *AffinityMask = nullptr ///< CPUs or processors the new
0141                                         /// program shall run on.
0142   );
0143 
0144   /// Similar to \ref ExecuteAndWait, but returns immediately.
0145   /// \returns The \ref ProcessInfo of the newly launched process.
0146   /// \note On Microsoft Windows systems, users will need to either call
0147   /// \ref Wait until the process has finished executing or win32's CloseHandle
0148   /// API on ProcessInfo.ProcessHandle to avoid memory leaks.
0149   ProcessInfo ExecuteNoWait(
0150       StringRef Program, ArrayRef<StringRef> Args,
0151       std::optional<ArrayRef<StringRef>> Env,
0152       ArrayRef<std::optional<StringRef>> Redirects = {},
0153       unsigned MemoryLimit = 0, std::string *ErrMsg = nullptr,
0154       bool *ExecutionFailed = nullptr, BitVector *AffinityMask = nullptr,
0155       /// If true the executed program detatches from the controlling
0156       /// terminal. I/O streams such as llvm::outs, llvm::errs, and stdin will
0157       /// be closed until redirected to another output location
0158       bool DetachProcess = false);
0159 
0160   /// Return true if the given arguments fit within system-specific
0161   /// argument length limits.
0162   bool commandLineFitsWithinSystemLimits(StringRef Program,
0163                                          ArrayRef<StringRef> Args);
0164 
0165   /// Return true if the given arguments fit within system-specific
0166   /// argument length limits.
0167   bool commandLineFitsWithinSystemLimits(StringRef Program,
0168                                          ArrayRef<const char *> Args);
0169 
0170   /// File encoding options when writing contents that a non-UTF8 tool will
0171   /// read (on Windows systems). For UNIX, we always use UTF-8.
0172   enum WindowsEncodingMethod {
0173     /// UTF-8 is the LLVM native encoding, being the same as "do not perform
0174     /// encoding conversion".
0175     WEM_UTF8,
0176     WEM_CurrentCodePage,
0177     WEM_UTF16
0178   };
0179 
0180   /// Saves the UTF8-encoded \p contents string into the file \p FileName
0181   /// using a specific encoding.
0182   ///
0183   /// This write file function adds the possibility to choose which encoding
0184   /// to use when writing a text file. On Windows, this is important when
0185   /// writing files with internationalization support with an encoding that is
0186   /// different from the one used in LLVM (UTF-8). We use this when writing
0187   /// response files, since GCC tools on MinGW only understand legacy code
0188   /// pages, and VisualStudio tools only understand UTF-16.
0189   /// For UNIX, using different encodings is silently ignored, since all tools
0190   /// work well with UTF-8.
0191   /// This function assumes that you only use UTF-8 *text* data and will convert
0192   /// it to your desired encoding before writing to the file.
0193   ///
0194   /// FIXME: We use EM_CurrentCodePage to write response files for GNU tools in
0195   /// a MinGW/MinGW-w64 environment, which has serious flaws but currently is
0196   /// our best shot to make gcc/ld understand international characters. This
0197   /// should be changed as soon as binutils fix this to support UTF16 on mingw.
0198   ///
0199   /// \returns non-zero error_code if failed
0200   std::error_code
0201   writeFileWithEncoding(StringRef FileName, StringRef Contents,
0202                         WindowsEncodingMethod Encoding = WEM_UTF8);
0203 
0204   /// This function waits for the process specified by \p PI to finish.
0205   /// \returns A \see ProcessInfo struct with Pid set to:
0206   /// \li The process id of the child process if the child process has changed
0207   /// state.
0208   /// \li 0 if the child process has not changed state.
0209   /// \note Users of this function should always check the ReturnCode member of
0210   /// the \see ProcessInfo returned from this function.
0211   ProcessInfo
0212   Wait(const ProcessInfo &PI, ///< The child process that should be waited on.
0213        std::optional<unsigned> SecondsToWait, ///< If std::nullopt, waits until
0214        ///< child has terminated.
0215        ///< If a value, this specifies the amount of time to wait for the child
0216        ///< process. If the time expires, and \p Polling is false, the child is
0217        ///< killed and this < function returns. If the time expires and \p
0218        ///< Polling is true, the child is resumed.
0219        ///<
0220        ///< If zero, this function will perform a non-blocking
0221        ///< wait on the child process.
0222        std::string *ErrMsg = nullptr, ///< If non-zero, provides a pointer to a
0223        ///< string instance in which error messages will be returned. If the
0224        ///< string is non-empty upon return an error occurred while invoking the
0225        ///< program.
0226        std::optional<ProcessStatistics> *ProcStat =
0227            nullptr, ///< If non-zero, provides
0228        /// a pointer to a structure in which process execution statistics will
0229        /// be stored.
0230 
0231        bool Polling = false ///< If true, do not kill the process on timeout.
0232   );
0233 
0234   /// Print a command argument, and optionally quote it.
0235   void printArg(llvm::raw_ostream &OS, StringRef Arg, bool Quote);
0236 
0237 #if defined(_WIN32)
0238   /// Given a list of command line arguments, quote and escape them as necessary
0239   /// to build a single flat command line appropriate for calling CreateProcess
0240   /// on
0241   /// Windows.
0242   ErrorOr<std::wstring> flattenWindowsCommandLine(ArrayRef<StringRef> Args);
0243 #endif
0244   }
0245 }
0246 
0247 #endif