LLVM 24.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 /// Return CPU time and peak memory of this process so far, like
79 /// sys::Wait reports for a child, or std::nullopt where unsupported.
80 LLVM_ABI static std::optional<ProcessStatistics> getStatistics();
81
82 /// This static function will set \p user_time to the amount of CPU time
83 /// spent in user (non-kernel) mode and \p sys_time to the amount of CPU
84 /// time spent in system (kernel) mode. If the operating system does not
85 /// support collection of these metrics, a zero duration will be for both
86 /// values.
87 /// \param elapsed Returns the system_clock::now() giving current time
88 /// \param user_time Returns the current amount of user time for the process
89 /// \param sys_time Returns the current amount of system time for the process
90 LLVM_ABI static void GetTimeUsage(TimePoint<> &elapsed,
91 std::chrono::nanoseconds &user_time,
92 std::chrono::nanoseconds &sys_time);
93
94 /// This function makes the necessary calls to the operating system to
95 /// prevent core files or any other kind of large memory dumps that can
96 /// occur when a program fails.
97 /// Prevent core file generation.
99
100 /// true if PreventCoreFiles has been called, false otherwise.
101 LLVM_ABI static bool AreCoreFilesPrevented();
102
103 // This function returns the environment variable \arg name's value as a UTF-8
104 // string. \arg Name is assumed to be in UTF-8 encoding too.
105 LLVM_ABI static std::optional<std::string> GetEnv(StringRef name);
106
107 /// This function searches for an existing file in the list of directories
108 /// in a PATH like environment variable, and returns the first file found,
109 /// according to the order of the entries in the PATH like environment
110 /// variable. If an ignore list is specified, then any folder which is in
111 /// the PATH like environment variable but is also in IgnoreList is not
112 /// considered.
113 LLVM_ABI static std::optional<std::string>
114 FindInEnvPath(StringRef EnvName, StringRef FileName,
115 ArrayRef<std::string> IgnoreList,
116 char Separator = EnvPathSeparator);
117
118 LLVM_ABI static std::optional<std::string>
119 FindInEnvPath(StringRef EnvName, StringRef FileName,
120 char Separator = EnvPathSeparator);
121
122 // This functions ensures that the standard file descriptors (input, output,
123 // and error) are properly mapped to a file descriptor before we use any of
124 // them. This should only be called by standalone programs, library
125 // components should not call this.
126 LLVM_ABI static std::error_code FixupStandardFileDescriptors();
127
128 // This function safely closes a file descriptor. It is not safe to retry
129 // close(2) when it returns with errno equivalent to EINTR; this is because
130 // *nixen cannot agree if the file descriptor is, in fact, closed when this
131 // occurs.
132 //
133 // N.B. Some operating systems, due to thread cancellation, cannot properly
134 // guarantee that it will or will not be closed one way or the other!
135 LLVM_ABI static std::error_code SafelyCloseFileDescriptor(int FD);
136
137 /// This function determines if the standard input is connected directly
138 /// to a user's input (keyboard probably), rather than coming from a file
139 /// or pipe.
141
142 /// This function determines if the standard output is connected to a
143 /// "tty" or "console" window. That is, the output would be displayed to
144 /// the user rather than being put on a pipe or stored in a file.
146
147 /// This function determines if the standard error is connected to a
148 /// "tty" or "console" window. That is, the output would be displayed to
149 /// the user rather than being put on a pipe or stored in a file.
151
152 /// This function determines if the given file descriptor is connected to
153 /// a "tty" or "console" window. That is, the output would be displayed to
154 /// the user rather than being put on a pipe or stored in a file.
156
157 /// This function determines if the given file descriptor is displayd and
158 /// supports colors.
160
161 /// This function determines the number of columns in the window
162 /// if standard output is connected to a "tty" or "console"
163 /// window. If standard output is not connected to a tty or
164 /// console, or if the number of columns cannot be determined,
165 /// this routine returns zero.
166 LLVM_ABI static unsigned StandardOutColumns();
167
168 /// This function determines the number of columns in the window
169 /// if standard error is connected to a "tty" or "console"
170 /// window. If standard error is not connected to a tty or
171 /// console, or if the number of columns cannot be determined,
172 /// this routine returns zero.
173 LLVM_ABI static unsigned StandardErrColumns();
174
175 /// This function determines whether the terminal connected to standard
176 /// output supports colors. If standard output is not connected to a
177 /// terminal, this function returns false.
179
180 /// This function determines whether the terminal connected to standard
181 /// error supports colors. If standard error is not connected to a
182 /// terminal, this function returns false.
184
185 /// Enables or disables whether ANSI escape sequences are used to output
186 /// colors. This only has an effect on Windows.
187 /// Note: Setting this option is not thread-safe and should only be done
188 /// during initialization.
189 LLVM_ABI static void UseANSIEscapeCodes(bool enable);
190
191 /// Whether changing colors requires the output to be flushed.
192 /// This is needed on systems that don't support escape sequences for
193 /// changing colors.
195
196 /// This function returns the colorcode escape sequences.
197 /// If ColorNeedsFlush() is true then this function will change the colors
198 /// and return an empty escape sequence. In that case it is the
199 /// responsibility of the client to flush the output stream prior to
200 /// calling this function.
201 LLVM_ABI static const char *OutputColor(char c, bool bold, bool bg);
202
203 /// Same as OutputColor, but only enables the bold attribute.
204 LLVM_ABI static const char *OutputBold(bool bg);
205
206 /// This function returns the escape sequence to reverse forground and
207 /// background colors.
208 LLVM_ABI static const char *OutputReverse();
209
210 /// Resets the terminals colors, or returns an escape sequence to do so.
211 LLVM_ABI static const char *ResetColor();
212
213 /// Get the result of a process wide random number generator. The
214 /// generator will be automatically seeded in non-deterministic fashion.
215 LLVM_ABI static unsigned GetRandomNumber();
216
217 /// Equivalent to ::exit(), except when running inside a CrashRecoveryContext.
218 /// In that case, the control flow will resume after RunSafely(), like for a
219 /// crash, rather than exiting the current process.
220 /// Use \arg NoCleanup for calling _exit() instead of exit().
221 [[noreturn]] LLVM_ABI static void Exit(int RetCode, bool NoCleanup = false);
222
223private:
224 [[noreturn]] static void ExitNoCleanup(int RetCode);
225};
226
227}
228}
229
230#endif
#define LLVM_ABI
Definition Compiler.h:211
static const char * name
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Tagged union holding either a T or a Error.
Definition Error.h:485
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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 std::optional< ProcessStatistics > getStatistics()
Return CPU time and peak memory of this process so far, like sys::Wait reports for a child,...
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.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106