LLVM 22.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/Support/Chrono.h"
30#include "llvm/Support/Error.h"
32#include <optional>
33#include <system_error>
34
35namespace llvm {
36template <typename T> class ArrayRef;
37class StringRef;
38
39namespace sys {
40
41
42/// A collection of legacy interfaces for querying information about the
43/// current executing process.
44class Process {
45public:
46 using Pid = int32_t;
47
48 /// Get the process's identifier.
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 LLVM_ABI 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 LLVM_ABI 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.
95
96 /// true if PreventCoreFiles has been called, false otherwise.
97 LLVM_ABI 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.
101 LLVM_ABI static std::optional<std::string> GetEnv(StringRef name);
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.
109 LLVM_ABI static std::optional<std::string>
110 FindInEnvPath(StringRef EnvName, StringRef FileName,
111 ArrayRef<std::string> IgnoreList,
112 char Separator = EnvPathSeparator);
113
114 LLVM_ABI static std::optional<std::string>
115 FindInEnvPath(StringRef EnvName, 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 LLVM_ABI 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 LLVM_ABI 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.
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.
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.
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.
152
153 /// This function determines if the given file descriptor is displayd and
154 /// supports colors.
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 LLVM_ABI 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 LLVM_ABI 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.
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.
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 LLVM_ABI 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.
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 LLVM_ABI static const char *OutputColor(char c, bool bold, bool bg);
198
199 /// Same as OutputColor, but only enables the bold attribute.
200 LLVM_ABI static const char *OutputBold(bool bg);
201
202 /// This function returns the escape sequence to reverse forground and
203 /// background colors.
204 LLVM_ABI static const char *OutputReverse();
205
206 /// Resets the terminals colors, or returns an escape sequence to do so.
207 LLVM_ABI 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 LLVM_ABI 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]] LLVM_ABI static void Exit(int RetCode, bool NoCleanup = false);
218
219private:
220 [[noreturn]] static void ExitNoCleanup(int RetCode);
221};
222
223}
224}
225
226#endif
#define LLVM_ABI
Definition: Compiler.h:213
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)
static const char * name
Definition: SMEABIPass.cpp:52
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Tagged union holding either a T or a Error.
Definition: Error.h:485
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
A collection of legacy interfaces for querying information about the current executing process.
Definition: Process.h:44
static LLVM_ABI void UseANSIEscapeCodes(bool enable)
Enables or disables whether ANSI escape sequences are used to output colors.
static LLVM_ABI std::error_code SafelyCloseFileDescriptor(int FD)
static LLVM_ABI 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...
static LLVM_ABI std::error_code FixupStandardFileDescriptors()
static LLVM_ABI Pid getProcessId()
Get the process's identifier.
static LLVM_ABI size_t GetMallocUsage()
Return process memory usage.
static LLVM_ABI bool ColorNeedsFlush()
Whether changing colors requires the output to be flushed.
static LLVM_ABI std::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:39
static LLVM_ABI void Exit(int RetCode, bool NoCleanup=false)
Equivalent to ::exit(), except when running inside a CrashRecoveryContext.
Definition: Process.cpp:110
static LLVM_ABI const char * ResetColor()
Resets the terminals colors, or returns an escape sequence to do so.
static LLVM_ABI unsigned GetRandomNumber()
Get the result of a process wide random number generator.
static LLVM_ABI bool FileDescriptorIsDisplayed(int fd)
This function determines if the given file descriptor is connected to a "tty" or "console" window.
static LLVM_ABI Expected< unsigned > getPageSize()
Get the process's page size.
static LLVM_ABI const char * OutputColor(char c, bool bold, bool bg)
This function returns the colorcode escape sequences.
static LLVM_ABI const char * OutputBold(bool bg)
Same as OutputColor, but only enables the bold attribute.
static unsigned getPageSizeEstimate()
Get the process's estimated page size.
Definition: Process.h:62
static LLVM_ABI unsigned StandardErrColumns()
This function determines the number of columns in the window if standard error is connected to a "tty...
static LLVM_ABI bool AreCoreFilesPrevented()
true if PreventCoreFiles has been called, false otherwise.
Definition: Process.cpp:108
static LLVM_ABI std::optional< std::string > GetEnv(StringRef name)
static LLVM_ABI bool FileDescriptorHasColors(int fd)
This function determines if the given file descriptor is displayd and supports colors.
static LLVM_ABI bool StandardInIsUserInput()
This function determines if the standard input is connected directly to a user's input (keyboard prob...
static LLVM_ABI void PreventCoreFiles()
This function makes the necessary calls to the operating system to prevent core files or any other ki...
static LLVM_ABI bool StandardErrHasColors()
This function determines whether the terminal connected to standard error supports colors.
static LLVM_ABI const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
static LLVM_ABI bool StandardErrIsDisplayed()
This function determines if the standard error is connected to a "tty" or "console" window.
static LLVM_ABI bool StandardOutHasColors()
This function determines whether the terminal connected to standard output supports colors.
static LLVM_ABI unsigned StandardOutColumns()
This function determines the number of columns in the window if standard output is connected to a "tt...
static LLVM_ABI bool StandardOutIsDisplayed()
This function determines if the standard output is connected to a "tty" or "console" window.
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition: Chrono.h:34
const char EnvPathSeparator
This is the OS-specific separator for PATH like environment variables:
Definition: Program.h:33
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
ArrayRef(const T &OneElt) -> ArrayRef< T >
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1083