LLVM  14.0.0git
Process.h
Go to the documentation of this file.
1 //===- llvm/Support/Process.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 /// \file
9 ///
10 /// Provides a library for accessing information about this process and other
11 /// processes on the operating system. Also provides means of spawning
12 /// subprocess for commands. The design of this library is modeled after the
13 /// proposed design of the Boost.Process library, and is design specifically to
14 /// follow the style of standard libraries and potentially become a proposal
15 /// for a standard library.
16 ///
17 /// This file declares the llvm::sys::Process class which contains a collection
18 /// of legacy static interfaces for extracting various information about the
19 /// current process. The goal is to migrate users of this API over to the new
20 /// interfaces.
21 ///
22 //===----------------------------------------------------------------------===//
23 
24 #ifndef LLVM_SUPPORT_PROCESS_H
25 #define LLVM_SUPPORT_PROCESS_H
26 
27 #include "llvm/ADT/Optional.h"
29 #include "llvm/Support/Chrono.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Error.h"
32 #include "llvm/Support/Program.h"
33 #include <system_error>
34 
35 namespace llvm {
36 template <typename T> class ArrayRef;
37 class StringRef;
38 
39 namespace sys {
40 
41 
42 /// A collection of legacy interfaces for querying information about the
43 /// current executing process.
44 class Process {
45 public:
46  using Pid = int32_t;
47 
48  /// Get the process's identifier.
49  static Pid getProcessId();
50 
51  /// Get the process's page size.
52  /// This may fail if the underlying syscall returns an error. In most cases,
53  /// page size information is used for optimization, and this error can be
54  /// safely discarded by calling consumeError, and an estimated page size
55  /// substituted instead.
57 
58  /// Get the process's estimated page size.
59  /// This function always succeeds, but if the underlying syscall to determine
60  /// the page size fails then this will silently return an estimated page size.
61  /// The estimated page size is guaranteed to be a power of 2.
62  static unsigned getPageSizeEstimate() {
63  if (auto PageSize = getPageSize())
64  return *PageSize;
65  else {
66  consumeError(PageSize.takeError());
67  return 4096;
68  }
69  }
70 
71  /// Return process memory usage.
72  /// This static function will return the total amount of memory allocated
73  /// by the process. This only counts the memory allocated via the malloc,
74  /// calloc and realloc functions and includes any "free" holes in the
75  /// allocated space.
76  static size_t GetMallocUsage();
77 
78  /// This static function will set \p user_time to the amount of CPU time
79  /// spent in user (non-kernel) mode and \p sys_time to the amount of CPU
80  /// time spent in system (kernel) mode. If the operating system does not
81  /// support collection of these metrics, a zero duration will be for both
82  /// values.
83  /// \param elapsed Returns the system_clock::now() giving current time
84  /// \param user_time Returns the current amount of user time for the process
85  /// \param sys_time Returns the current amount of system time for the process
86  static void GetTimeUsage(TimePoint<> &elapsed,
87  std::chrono::nanoseconds &user_time,
88  std::chrono::nanoseconds &sys_time);
89 
90  /// This function makes the necessary calls to the operating system to
91  /// prevent core files or any other kind of large memory dumps that can
92  /// occur when a program fails.
93  /// Prevent core file generation.
94  static void PreventCoreFiles();
95 
96  /// true if PreventCoreFiles has been called, false otherwise.
97  static bool AreCoreFilesPrevented();
98 
99  // This function returns the environment variable \arg name's value as a UTF-8
100  // string. \arg Name is assumed to be in UTF-8 encoding too.
102 
103  /// This function searches for an existing file in the list of directories
104  /// in a PATH like environment variable, and returns the first file found,
105  /// according to the order of the entries in the PATH like environment
106  /// variable. If an ignore list is specified, then any folder which is in
107  /// the PATH like environment variable but is also in IgnoreList is not
108  /// considered.
110  StringRef FileName,
111  ArrayRef<std::string> IgnoreList,
112  char Separator = EnvPathSeparator);
113 
115  StringRef FileName,
116  char Separator = EnvPathSeparator);
117 
118  // This functions ensures that the standard file descriptors (input, output,
119  // and error) are properly mapped to a file descriptor before we use any of
120  // them. This should only be called by standalone programs, library
121  // components should not call this.
122  static std::error_code FixupStandardFileDescriptors();
123 
124  // This function safely closes a file descriptor. It is not safe to retry
125  // close(2) when it returns with errno equivalent to EINTR; this is because
126  // *nixen cannot agree if the file descriptor is, in fact, closed when this
127  // occurs.
128  //
129  // N.B. Some operating systems, due to thread cancellation, cannot properly
130  // guarantee that it will or will not be closed one way or the other!
131  static std::error_code SafelyCloseFileDescriptor(int FD);
132 
133  /// This function determines if the standard input is connected directly
134  /// to a user's input (keyboard probably), rather than coming from a file
135  /// or pipe.
136  static bool StandardInIsUserInput();
137 
138  /// This function determines if the standard output is connected to a
139  /// "tty" or "console" window. That is, the output would be displayed to
140  /// the user rather than being put on a pipe or stored in a file.
141  static bool StandardOutIsDisplayed();
142 
143  /// This function determines if the standard error is connected to a
144  /// "tty" or "console" window. That is, the output would be displayed to
145  /// the user rather than being put on a pipe or stored in a file.
146  static bool StandardErrIsDisplayed();
147 
148  /// This function determines if the given file descriptor is connected to
149  /// a "tty" or "console" window. That is, the output would be displayed to
150  /// the user rather than being put on a pipe or stored in a file.
151  static bool FileDescriptorIsDisplayed(int fd);
152 
153  /// This function determines if the given file descriptor is displayd and
154  /// supports colors.
155  static bool FileDescriptorHasColors(int fd);
156 
157  /// This function determines the number of columns in the window
158  /// if standard output is connected to a "tty" or "console"
159  /// window. If standard output is not connected to a tty or
160  /// console, or if the number of columns cannot be determined,
161  /// this routine returns zero.
162  static unsigned StandardOutColumns();
163 
164  /// This function determines the number of columns in the window
165  /// if standard error is connected to a "tty" or "console"
166  /// window. If standard error is not connected to a tty or
167  /// console, or if the number of columns cannot be determined,
168  /// this routine returns zero.
169  static unsigned StandardErrColumns();
170 
171  /// This function determines whether the terminal connected to standard
172  /// output supports colors. If standard output is not connected to a
173  /// terminal, this function returns false.
174  static bool StandardOutHasColors();
175 
176  /// This function determines whether the terminal connected to standard
177  /// error supports colors. If standard error is not connected to a
178  /// terminal, this function returns false.
179  static bool StandardErrHasColors();
180 
181  /// Enables or disables whether ANSI escape sequences are used to output
182  /// colors. This only has an effect on Windows.
183  /// Note: Setting this option is not thread-safe and should only be done
184  /// during initialization.
185  static void UseANSIEscapeCodes(bool enable);
186 
187  /// Whether changing colors requires the output to be flushed.
188  /// This is needed on systems that don't support escape sequences for
189  /// changing colors.
190  static bool ColorNeedsFlush();
191 
192  /// This function returns the colorcode escape sequences.
193  /// If ColorNeedsFlush() is true then this function will change the colors
194  /// and return an empty escape sequence. In that case it is the
195  /// responsibility of the client to flush the output stream prior to
196  /// calling this function.
197  static const char *OutputColor(char c, bool bold, bool bg);
198 
199  /// Same as OutputColor, but only enables the bold attribute.
200  static const char *OutputBold(bool bg);
201 
202  /// This function returns the escape sequence to reverse forground and
203  /// background colors.
204  static const char *OutputReverse();
205 
206  /// Resets the terminals colors, or returns an escape sequence to do so.
207  static const char *ResetColor();
208 
209  /// Get the result of a process wide random number generator. The
210  /// generator will be automatically seeded in non-deterministic fashion.
211  static unsigned GetRandomNumber();
212 
213  /// Equivalent to ::exit(), except when running inside a CrashRecoveryContext.
214  /// In that case, the control flow will resume after RunSafely(), like for a
215  /// crash, rather than exiting the current process.
216  /// Use \arg NoCleanup for calling _exit() instead of exit().
217  [[noreturn]] static void Exit(int RetCode, bool NoCleanup = false);
218 
219 private:
220  [[noreturn]] static void ExitNoCleanup(int RetCode);
221 };
222 
223 }
224 }
225 
226 #endif
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
Optional.h
llvm::sys::Process::UseANSIEscapeCodes
static void UseANSIEscapeCodes(bool enable)
Enables or disables whether ANSI escape sequences are used to output colors.
llvm::sys::Process::StandardErrColumns
static unsigned StandardErrColumns()
This function determines the number of columns in the window if standard error is connected to a "tty...
Error.h
llvm::sys::Process::PreventCoreFiles
static void PreventCoreFiles()
This function makes the necessary calls to the operating system to prevent core files or any other ki...
llvm::Optional< std::string >
llvm::sys::Process::Pid
int32_t Pid
Definition: Process.h:46
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
llvm::consumeError
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1035
llvm::sys::TimePoint
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition: Chrono.h:33
Chrono.h
llvm::sys::Process
A collection of legacy interfaces for querying information about the current executing process.
Definition: Process.h:44
llvm::sys::EnvPathSeparator
const char EnvPathSeparator
This is the OS-specific separator for PATH like environment variables:
Definition: Program.h:32
PageSize
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096), cl::Hidden)
llvm::sys::Process::StandardOutHasColors
static bool StandardOutHasColors()
This function determines whether the terminal connected to standard output supports colors.
llvm::sys::Process::GetRandomNumber
static unsigned GetRandomNumber()
Get the result of a process wide random number generator.
llvm::sys::Process::GetTimeUsage
static void GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time, std::chrono::nanoseconds &sys_time)
This static function will set user_time to the amount of CPU time spent in user (non-kernel) mode and...
c
the resulting code requires compare and branches when and if the revised code is with conditional branches instead of More there is a byte word extend before each where there should be only and the condition codes are not remembered when the same two values are compared twice More LSR enhancements i8 and i32 load store addressing modes are identical int int c
Definition: README.txt:418
AllocatorBase.h
llvm::sys::Process::OutputBold
static const char * OutputBold(bool bg)
Same as OutputColor, but only enables the bold attribute.
llvm::sys::Process::SafelyCloseFileDescriptor
static std::error_code SafelyCloseFileDescriptor(int FD)
llvm::sys::Process::FileDescriptorHasColors
static bool FileDescriptorHasColors(int fd)
This function determines if the given file descriptor is displayd and supports colors.
llvm::sys::Process::ResetColor
static const char * ResetColor()
Resets the terminals colors, or returns an escape sequence to do so.
llvm::sys::Process::OutputColor
static const char * OutputColor(char c, bool bold, bool bg)
This function returns the colorcode escape sequences.
llvm::sys::Process::getPageSize
static Expected< unsigned > getPageSize()
Get the process's page size.
llvm::sys::Process::GetEnv
static Optional< std::string > GetEnv(StringRef name)
llvm::sys::Process::AreCoreFilesPrevented
static bool AreCoreFilesPrevented()
true if PreventCoreFiles has been called, false otherwise.
Definition: Process.cpp:93
llvm::ArrayRef< std::string >
llvm::sys::Process::StandardErrHasColors
static bool StandardErrHasColors()
This function determines whether the terminal connected to standard error supports colors.
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
llvm::sys::Process::Exit
static void Exit(int RetCode, bool NoCleanup=false)
Equivalent to exit(), except when running inside a CrashRecoveryContext.
Definition: Process.cpp:95
llvm::sys::Process::OutputReverse
static const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
name
static const char * name
Definition: SVEIntrinsicOpts.cpp:78
llvm::sys::Process::StandardOutIsDisplayed
static bool StandardOutIsDisplayed()
This function determines if the standard output is connected to a "tty" or "console" window.
llvm::sys::Process::StandardOutColumns
static unsigned StandardOutColumns()
This function determines the number of columns in the window if standard output is connected to a "tt...
llvm::sys::Process::FileDescriptorIsDisplayed
static bool FileDescriptorIsDisplayed(int fd)
This function determines if the given file descriptor is connected to a "tty" or "console" window.
llvm::sys::Process::ColorNeedsFlush
static bool ColorNeedsFlush()
Whether changing colors requires the output to be flushed.
llvm::sys::Process::getProcessId
static Pid getProcessId()
Get the process's identifier.
llvm::sys::Process::FixupStandardFileDescriptors
static std::error_code FixupStandardFileDescriptors()
Program.h
DataTypes.h
llvm::sys::Process::getPageSizeEstimate
static unsigned getPageSizeEstimate()
Get the process's estimated page size.
Definition: Process.h:62
llvm::sys::Process::GetMallocUsage
static size_t GetMallocUsage()
Return process memory usage.
llvm::sys::Process::StandardErrIsDisplayed
static bool StandardErrIsDisplayed()
This function determines if the standard error is connected to a "tty" or "console" window.
llvm::sys::Process::FindInEnvPath
static Optional< std::string > FindInEnvPath(StringRef EnvName, StringRef FileName, ArrayRef< std::string > IgnoreList, char Separator=EnvPathSeparator)
This function searches for an existing file in the list of directories in a PATH like environment var...
Definition: Process.cpp:38
llvm::sys::Process::StandardInIsUserInput
static bool StandardInIsUserInput()
This function determines if the standard input is connected directly to a user's input (keyboard prob...