Process.h 9.8 KB

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