Process.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. #ifndef LLVM_SUPPORT_PROCESS_H
  24. #define LLVM_SUPPORT_PROCESS_H
  25. #include "llvm/ADT/Optional.h"
  26. #include "llvm/Support/AllocatorBase.h"
  27. #include "llvm/Support/Chrono.h"
  28. #include "llvm/Support/DataTypes.h"
  29. #include "llvm/Support/Error.h"
  30. #include "llvm/Support/Program.h"
  31. #include <system_error>
  32. namespace llvm {
  33. template <typename T> class ArrayRef;
  34. class StringRef;
  35. namespace sys {
  36. /// A collection of legacy interfaces for querying information about the
  37. /// current executing process.
  38. class Process {
  39. public:
  40. using Pid = int32_t;
  41. /// Get the process's identifier.
  42. static Pid getProcessId();
  43. /// Get the process's page size.
  44. /// This may fail if the underlying syscall returns an error. In most cases,
  45. /// page size information is used for optimization, and this error can be
  46. /// safely discarded by calling consumeError, and an estimated page size
  47. /// substituted instead.
  48. static Expected<unsigned> getPageSize();
  49. /// Get the process's estimated page size.
  50. /// This function always succeeds, but if the underlying syscall to determine
  51. /// the page size fails then this will silently return an estimated page size.
  52. /// The estimated page size is guaranteed to be a power of 2.
  53. static unsigned getPageSizeEstimate() {
  54. if (auto PageSize = getPageSize())
  55. return *PageSize;
  56. else {
  57. consumeError(PageSize.takeError());
  58. return 4096;
  59. }
  60. }
  61. /// Return process memory usage.
  62. /// This static function will return the total amount of memory allocated
  63. /// by the process. This only counts the memory allocated via the malloc,
  64. /// calloc and realloc functions and includes any "free" holes in the
  65. /// allocated space.
  66. static size_t GetMallocUsage();
  67. /// This static function will set \p user_time to the amount of CPU time
  68. /// spent in user (non-kernel) mode and \p sys_time to the amount of CPU
  69. /// time spent in system (kernel) mode. If the operating system does not
  70. /// support collection of these metrics, a zero duration will be for both
  71. /// values.
  72. /// \param elapsed Returns the system_clock::now() giving current time
  73. /// \param user_time Returns the current amount of user time for the process
  74. /// \param sys_time Returns the current amount of system time for the process
  75. static void GetTimeUsage(TimePoint<> &elapsed,
  76. std::chrono::nanoseconds &user_time,
  77. std::chrono::nanoseconds &sys_time);
  78. /// This function makes the necessary calls to the operating system to
  79. /// prevent core files or any other kind of large memory dumps that can
  80. /// occur when a program fails.
  81. /// Prevent core file generation.
  82. static void PreventCoreFiles();
  83. /// true if PreventCoreFiles has been called, false otherwise.
  84. static bool AreCoreFilesPrevented();
  85. // This function returns the environment variable \arg name's value as a UTF-8
  86. // string. \arg Name is assumed to be in UTF-8 encoding too.
  87. static Optional<std::string> GetEnv(StringRef name);
  88. /// This function searches for an existing file in the list of directories
  89. /// in a PATH like environment variable, and returns the first file found,
  90. /// according to the order of the entries in the PATH like environment
  91. /// variable. If an ignore list is specified, then any folder which is in
  92. /// the PATH like environment variable but is also in IgnoreList is not
  93. /// considered.
  94. static Optional<std::string> FindInEnvPath(StringRef EnvName,
  95. StringRef FileName,
  96. ArrayRef<std::string> IgnoreList,
  97. char Separator = EnvPathSeparator);
  98. static Optional<std::string> FindInEnvPath(StringRef EnvName,
  99. StringRef FileName,
  100. char Separator = EnvPathSeparator);
  101. // This functions ensures that the standard file descriptors (input, output,
  102. // and error) are properly mapped to a file descriptor before we use any of
  103. // them. This should only be called by standalone programs, library
  104. // components should not call this.
  105. static std::error_code FixupStandardFileDescriptors();
  106. // This function safely closes a file descriptor. It is not safe to retry
  107. // close(2) when it returns with errno equivalent to EINTR; this is because
  108. // *nixen cannot agree if the file descriptor is, in fact, closed when this
  109. // occurs.
  110. //
  111. // N.B. Some operating systems, due to thread cancellation, cannot properly
  112. // guarantee that it will or will not be closed one way or the other!
  113. static std::error_code SafelyCloseFileDescriptor(int FD);
  114. /// This function determines if the standard input is connected directly
  115. /// to a user's input (keyboard probably), rather than coming from a file
  116. /// or pipe.
  117. static bool StandardInIsUserInput();
  118. /// This function determines if the standard output is connected to a
  119. /// "tty" or "console" window. That is, the output would be displayed to
  120. /// the user rather than being put on a pipe or stored in a file.
  121. static bool StandardOutIsDisplayed();
  122. /// This function determines if the standard error is connected to a
  123. /// "tty" or "console" window. That is, the output would be displayed to
  124. /// the user rather than being put on a pipe or stored in a file.
  125. static bool StandardErrIsDisplayed();
  126. /// This function determines if the given file descriptor is connected to
  127. /// a "tty" or "console" window. That is, the output would be displayed to
  128. /// the user rather than being put on a pipe or stored in a file.
  129. static bool FileDescriptorIsDisplayed(int fd);
  130. /// This function determines if the given file descriptor is displayd and
  131. /// supports colors.
  132. static bool FileDescriptorHasColors(int fd);
  133. /// This function determines the number of columns in the window
  134. /// if standard output is connected to a "tty" or "console"
  135. /// window. If standard output is not connected to a tty or
  136. /// console, or if the number of columns cannot be determined,
  137. /// this routine returns zero.
  138. static unsigned StandardOutColumns();
  139. /// This function determines the number of columns in the window
  140. /// if standard error is connected to a "tty" or "console"
  141. /// window. If standard error is not connected to a tty or
  142. /// console, or if the number of columns cannot be determined,
  143. /// this routine returns zero.
  144. static unsigned StandardErrColumns();
  145. /// This function determines whether the terminal connected to standard
  146. /// output supports colors. If standard output is not connected to a
  147. /// terminal, this function returns false.
  148. static bool StandardOutHasColors();
  149. /// This function determines whether the terminal connected to standard
  150. /// error supports colors. If standard error is not connected to a
  151. /// terminal, this function returns false.
  152. static bool StandardErrHasColors();
  153. /// Enables or disables whether ANSI escape sequences are used to output
  154. /// colors. This only has an effect on Windows.
  155. /// Note: Setting this option is not thread-safe and should only be done
  156. /// during initialization.
  157. static void UseANSIEscapeCodes(bool enable);
  158. /// Whether changing colors requires the output to be flushed.
  159. /// This is needed on systems that don't support escape sequences for
  160. /// changing colors.
  161. static bool ColorNeedsFlush();
  162. /// This function returns the colorcode escape sequences.
  163. /// If ColorNeedsFlush() is true then this function will change the colors
  164. /// and return an empty escape sequence. In that case it is the
  165. /// responsibility of the client to flush the output stream prior to
  166. /// calling this function.
  167. static const char *OutputColor(char c, bool bold, bool bg);
  168. /// Same as OutputColor, but only enables the bold attribute.
  169. static const char *OutputBold(bool bg);
  170. /// This function returns the escape sequence to reverse forground and
  171. /// background colors.
  172. static const char *OutputReverse();
  173. /// Resets the terminals colors, or returns an escape sequence to do so.
  174. static const char *ResetColor();
  175. /// Get the result of a process wide random number generator. The
  176. /// generator will be automatically seeded in non-deterministic fashion.
  177. static unsigned GetRandomNumber();
  178. /// Equivalent to ::exit(), except when running inside a CrashRecoveryContext.
  179. /// In that case, the control flow will resume after RunSafely(), like for a
  180. /// crash, rather than exiting the current process.
  181. /// Use \arg NoCleanup for calling _exit() instead of exit().
  182. LLVM_ATTRIBUTE_NORETURN
  183. static void Exit(int RetCode, bool NoCleanup = false);
  184. private:
  185. LLVM_ATTRIBUTE_NORETURN
  186. static void ExitNoCleanup(int RetCode);
  187. };
  188. }
  189. }
  190. #endif