Process.h revision 2df178997d17474042e8c3704cc93ab2db6619bf
1//===- llvm/Support/Process.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/// \file
10///
11/// Provides a library for accessing information about this process and other
12/// processes on the operating system. Also provides means of spawning
13/// subprocess for commands. The design of this library is modeled after the
14/// proposed design of the Boost.Process library, and is design specifically to
15/// follow the style of standard libraries and potentially become a proposal
16/// for a standard library.
17///
18/// This file declares the llvm::sys::Process class which contains a collection
19/// of legacy static interfaces for extracting various information about the
20/// current process. The goal is to migrate users of this API over to the new
21/// interfaces.
22///
23//===----------------------------------------------------------------------===//
24
25#ifndef LLVM_SUPPORT_PROCESS_H
26#define LLVM_SUPPORT_PROCESS_H
27
28#include "llvm/ADT/Optional.h"
29#include "llvm/Config/llvm-config.h"
30#include "llvm/Support/Allocator.h"
31#include "llvm/Support/Chrono.h"
32#include "llvm/Support/DataTypes.h"
33#include <system_error>
34
35namespace llvm {
36template <typename T> class ArrayRef;
37class StringRef;
38
39namespace sys {
40
41
42/// \brief A collection of legacy interfaces for querying information about the
43/// current executing process.
44class Process {
45public:
46  static unsigned getPageSize();
47
48  /// \brief Return process memory usage.
49  /// This static function will return the total amount of memory allocated
50  /// by the process. This only counts the memory allocated via the malloc,
51  /// calloc and realloc functions and includes any "free" holes in the
52  /// allocated space.
53  static size_t GetMallocUsage();
54
55  /// This static function will set \p user_time to the amount of CPU time
56  /// spent in user (non-kernel) mode and \p sys_time to the amount of CPU
57  /// time spent in system (kernel) mode.  If the operating system does not
58  /// support collection of these metrics, a zero duration will be for both
59  /// values.
60  /// \param elapsed Returns the system_clock::now() giving current time
61  /// \param user_time Returns the current amount of user time for the process
62  /// \param sys_time Returns the current amount of system time for the process
63  static void GetTimeUsage(TimePoint<> &elapsed,
64                           std::chrono::nanoseconds &user_time,
65                           std::chrono::nanoseconds &sys_time);
66
67  /// This function makes the necessary calls to the operating system to
68  /// prevent core files or any other kind of large memory dumps that can
69  /// occur when a program fails.
70  /// @brief Prevent core file generation.
71  static void PreventCoreFiles();
72
73  /// \brief true if PreventCoreFiles has been called, false otherwise.
74  static bool AreCoreFilesPrevented();
75
76  // This function returns the environment variable \arg name's value as a UTF-8
77  // string. \arg Name is assumed to be in UTF-8 encoding too.
78  static Optional<std::string> GetEnv(StringRef name);
79
80  /// This function searches for an existing file in the list of directories
81  /// in a PATH like environment variable, and returns the first file found,
82  /// according to the order of the entries in the PATH like environment
83  /// variable.
84  static Optional<std::string> FindInEnvPath(const std::string& EnvName,
85                                             const std::string& FileName);
86
87  /// This function returns a SmallVector containing the arguments passed from
88  /// the operating system to the program.  This function expects to be handed
89  /// the vector passed in from main.
90  static std::error_code
91  GetArgumentVector(SmallVectorImpl<const char *> &Args,
92                    ArrayRef<const char *> ArgsFromMain,
93                    SpecificBumpPtrAllocator<char> &ArgAllocator);
94
95  // This functions ensures that the standard file descriptors (input, output,
96  // and error) are properly mapped to a file descriptor before we use any of
97  // them.  This should only be called by standalone programs, library
98  // components should not call this.
99  static std::error_code FixupStandardFileDescriptors();
100
101  // This function safely closes a file descriptor.  It is not safe to retry
102  // close(2) when it returns with errno equivalent to EINTR; this is because
103  // *nixen cannot agree if the file descriptor is, in fact, closed when this
104  // occurs.
105  //
106  // N.B. Some operating systems, due to thread cancellation, cannot properly
107  // guarantee that it will or will not be closed one way or the other!
108  static std::error_code SafelyCloseFileDescriptor(int FD);
109
110  /// This function determines if the standard input is connected directly
111  /// to a user's input (keyboard probably), rather than coming from a file
112  /// or pipe.
113  static bool StandardInIsUserInput();
114
115  /// This function determines if the standard output is connected to a
116  /// "tty" or "console" window. That is, the output would be displayed to
117  /// the user rather than being put on a pipe or stored in a file.
118  static bool StandardOutIsDisplayed();
119
120  /// This function determines if the standard error is connected to a
121  /// "tty" or "console" window. That is, the output would be displayed to
122  /// the user rather than being put on a pipe or stored in a file.
123  static bool StandardErrIsDisplayed();
124
125  /// This function determines if the given file descriptor is connected to
126  /// a "tty" or "console" window. That is, the output would be displayed to
127  /// the user rather than being put on a pipe or stored in a file.
128  static bool FileDescriptorIsDisplayed(int fd);
129
130  /// This function determines if the given file descriptor is displayd and
131  /// supports colors.
132  static bool FileDescriptorHasColors(int fd);
133
134  /// This function determines the number of columns in the window
135  /// if standard output is connected to a "tty" or "console"
136  /// window. If standard output is not connected to a tty or
137  /// console, or if the number of columns cannot be determined,
138  /// this routine returns zero.
139  static unsigned StandardOutColumns();
140
141  /// This function determines the number of columns in the window
142  /// if standard error is connected to a "tty" or "console"
143  /// window. If standard error is not connected to a tty or
144  /// console, or if the number of columns cannot be determined,
145  /// this routine returns zero.
146  static unsigned StandardErrColumns();
147
148  /// This function determines whether the terminal connected to standard
149  /// output supports colors. If standard output is not connected to a
150  /// terminal, this function returns false.
151  static bool StandardOutHasColors();
152
153  /// This function determines whether the terminal connected to standard
154  /// error supports colors. If standard error is not connected to a
155  /// terminal, this function returns false.
156  static bool StandardErrHasColors();
157
158  /// Enables or disables whether ANSI escape sequences are used to output
159  /// colors. This only has an effect on Windows.
160  /// Note: Setting this option is not thread-safe and should only be done
161  /// during initialization.
162  static void UseANSIEscapeCodes(bool enable);
163
164  /// Whether changing colors requires the output to be flushed.
165  /// This is needed on systems that don't support escape sequences for
166  /// changing colors.
167  static bool ColorNeedsFlush();
168
169  /// This function returns the colorcode escape sequences.
170  /// If ColorNeedsFlush() is true then this function will change the colors
171  /// and return an empty escape sequence. In that case it is the
172  /// responsibility of the client to flush the output stream prior to
173  /// calling this function.
174  static const char *OutputColor(char c, bool bold, bool bg);
175
176  /// Same as OutputColor, but only enables the bold attribute.
177  static const char *OutputBold(bool bg);
178
179  /// This function returns the escape sequence to reverse forground and
180  /// background colors.
181  static const char *OutputReverse();
182
183  /// Resets the terminals colors, or returns an escape sequence to do so.
184  static const char *ResetColor();
185
186  /// Get the result of a process wide random number generator. The
187  /// generator will be automatically seeded in non-deterministic fashion.
188  static unsigned GetRandomNumber();
189};
190
191}
192}
193
194#endif
195