Process.h 9.6 KB

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