xref: /aosp_15_r20/external/cronet/base/system/sys_info.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_SYSTEM_SYS_INFO_H_
6 #define BASE_SYSTEM_SYS_INFO_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <map>
12 #include <optional>
13 #include <string>
14 #include <string_view>
15 
16 #include "base/base_export.h"
17 #include "base/functional/callback_forward.h"
18 #include "base/gtest_prod_util.h"
19 #include "base/metrics/field_trial_params.h"
20 #include "base/time/time.h"
21 #include "build/build_config.h"
22 
23 #if BUILDFLAG(IS_MAC)
24 #include "base/feature_list.h"
25 #endif
26 
27 namespace base {
28 
29 #if BUILDFLAG(IS_MAC)
30 // When enabled, NumberOfProcessors() returns the number of physical processors
31 // instead of the number of logical processors if CPU security mitigations are
32 // enabled for the current process.
33 BASE_EXPORT BASE_DECLARE_FEATURE(kNumberOfCoresWithCpuSecurityMitigation);
34 #endif
35 
36 #if BUILDFLAG(IS_CHROMEOS_ASH)
37 // Strings for environment variables.
38 BASE_EXPORT extern const char kLsbReleaseKey[];
39 BASE_EXPORT extern const char kLsbReleaseTimeKey[];
40 #endif
41 
42 namespace debug {
43 FORWARD_DECLARE_TEST(SystemMetricsTest, ParseMeminfo);
44 }
45 
46 namespace test {
47 class ScopedAmountOfPhysicalMemoryOverride;
48 }
49 
50 class FilePath;
51 struct SystemMemoryInfoKB;
52 
53 class BASE_EXPORT SysInfo {
54  public:
55   // Returns the number of processors/cores available for the current
56   // application. This is typically the number of logical cores installed on the
57   // system, but could instead be the number of physical cores when
58   // SetCpuSecurityMitigationsEnabled() has been invoked to indicate that CPU
59   // security mitigations are enabled on Mac.
60   // On some platforms this may cache the resulting value in its implementation,
61   // e.g. on Linux/ChromeOS where this function cannot run in a sandbox and so
62   // a cached value must be returned.
63   static int NumberOfProcessors();
64 
65   // Returns the number of the most efficient logical processors for the current
66   // application. This is typically e-cores on Intel hybrid architecture, or
67   // LITTLE cores on ARM bit.LITTLE architecture.
68   // Returns 0 on symmetric architecture or when it failed to recognize.
69   // This function will cache the result value in its implementation.
70   static int NumberOfEfficientProcessors();
71 
72   // Return the number of bytes of physical memory on the current machine.
73   // If low-end device mode is manually enabled via command line flag, this
74   // will return the lesser of the actual physical memory, or 512MB.
75   static uint64_t AmountOfPhysicalMemory();
76 
77   // Return the number of bytes of current available physical memory on the
78   // machine.
79   // (The amount of memory that can be allocated without any significant
80   // impact on the system. It can lead to freeing inactive file-backed
81   // and/or speculative file-backed memory).
82   static uint64_t AmountOfAvailablePhysicalMemory();
83 
84   // Return the number of bytes of virtual memory of this process. A return
85   // value of zero means that there is no limit on the available virtual
86   // memory.
87   static uint64_t AmountOfVirtualMemory();
88 
89   // Return the number of megabytes of physical memory on the current machine.
AmountOfPhysicalMemoryMB()90   static int AmountOfPhysicalMemoryMB() {
91     return static_cast<int>(AmountOfPhysicalMemory() / 1024 / 1024);
92   }
93 
94   // Return the number of megabytes of available virtual memory, or zero if it
95   // is unlimited.
AmountOfVirtualMemoryMB()96   static int AmountOfVirtualMemoryMB() {
97     return static_cast<int>(AmountOfVirtualMemory() / 1024 / 1024);
98   }
99 
100   // Return the available disk space in bytes on the volume containing |path|,
101   // or -1 on failure.
102   static int64_t AmountOfFreeDiskSpace(const FilePath& path);
103 
104   // Return the total disk space in bytes on the volume containing |path|, or -1
105   // on failure.
106   static int64_t AmountOfTotalDiskSpace(const FilePath& path);
107 
108 #if BUILDFLAG(IS_FUCHSIA)
109   // Sets the total amount of disk space to report under the specified |path|.
110   // If |bytes| is -ve then any existing entry for |path| is removed.
111   static void SetAmountOfTotalDiskSpace(const FilePath& path, int64_t bytes);
112 #endif
113 
114   // Returns system uptime.
115   static TimeDelta Uptime();
116 
117   // Returns a descriptive string for the current machine model or an empty
118   // string if the machine model is unknown or an error occurred.
119   // e.g. "MacPro1,1" on Mac, "iPhone9,3" on iOS or "Nexus 5" on Android. Only
120   // implemented on macOS, iOS, Android, Chrome OS and Windows. This returns an
121   // empty string on other platforms.
122   //
123   // For macOS, a useful reference of the resulting strings returned by this
124   // function and their corresponding hardware can be found at
125   // https://everymac.com/systems/by_capability/mac-specs-by-machine-model-machine-id.html
126   //
127   // For iOS, corresponding hardware can be found at
128   // https://deviceatlas.com/resources/clientside/ios-hardware-identification
129   static std::string HardwareModelName();
130 
131 #if BUILDFLAG(IS_MAC)
132   struct HardwareModelNameSplit {
133     std::string category;
134     int model = 0;
135     int variant = 0;
136   };
137   // Hardware model names on the Mac are of the shape "Mac��,��" where the
138   // prefix is the general category, the �� is the model, and the �� is the
139   // variant. This function takes the hardware model name as returned by
140   // HardwareModelName() above, and returns it split into its constituent parts.
141   // Returns nullopt if the value cannot be parsed.
142   //
143   // /!\ WARNING
144   //
145   // This is NOT A USEFUL FUNCTION and SHOULD NOT BE USED. While the `model`
146   // value does inform as to what generation of hardware it is within the
147   // `category`, this is not useful in determining the capabilities of the
148   // hardware. Instead of using the `model` value, check the actual capabilities
149   // of the hardware to verify what it can do rather than relying on a hardware
150   // model name. In addition, while the `category` value used to have meaning
151   // and could be used to determine the type of hardware (e.g. desktop vs
152   // laptop), in 2022 Apple started using the generic category of "Mac", thus
153   // removing its usefulness when used alone. While the entire model string as
154   // returned by HardwareModelName() above can be useful for identifying a
155   // specific piece of equipment, splitting apart it is not useful.
156   //
157   // Do not add any further callers! When the aforementioned 2022-era hardware
158   // is the minimum requirement for Chromium, remove this function and adjust
159   // all callers appropriately.
160   static std::optional<HardwareModelNameSplit> SplitHardwareModelNameDoNotUse(
161       std::string_view name);
162 #endif
163 
164   struct HardwareInfo {
165     std::string manufacturer;
166     std::string model;
167   };
168   // Returns via |callback| a struct containing descriptive UTF-8 strings for
169   // the current machine manufacturer and model, or empty strings if the
170   // information is unknown or an error occurred. Implemented on Windows, macOS,
171   // iOS, Linux, Chrome OS and Android.
172   static void GetHardwareInfo(base::OnceCallback<void(HardwareInfo)> callback);
173 
174   // Returns the name of the host operating system.
175   static std::string OperatingSystemName();
176 
177   // Returns the version of the host operating system.
178   static std::string OperatingSystemVersion();
179 
180   // Retrieves detailed numeric values for the OS version.
181   // DON'T USE THIS ON THE MAC OR WINDOWS to determine the current OS release
182   // for OS version-specific feature checks and workarounds. If you must use an
183   // OS version check instead of a feature check, use
184   // base::mac::MacOSVersion()/MacOSMajorVersion() family from
185   // base/mac/mac_util.h, or base::win::GetVersion() from
186   // base/win/windows_version.h.
187   static void OperatingSystemVersionNumbers(int32_t* major_version,
188                                             int32_t* minor_version,
189                                             int32_t* bugfix_version);
190 
191   // Returns the architecture of the running operating system.
192   // Exact return value may differ across platforms.
193   // e.g. a 32-bit x86 kernel on a 64-bit capable CPU will return "x86",
194   //      whereas a x86-64 kernel on the same CPU will return "x86_64"
195   static std::string OperatingSystemArchitecture();
196 
197   // Returns the architecture of the running process, which might be different
198   // than the architecture returned by OperatingSystemArchitecture() (e.g.
199   // macOS Rosetta, a 32-bit binary on a 64-bit OS, etc).
200   // Will return one of: "x86", "x86_64", "ARM", "ARM_64", or an empty string if
201   // none of the above.
202   static std::string ProcessCPUArchitecture();
203 
204   // Returns the CPU model name of the system. If it can not be figured out,
205   // an empty string is returned.
206   // More detailed info can be obtained from base/cpu.h.
207   static std::string CPUModelName();
208 
209   // Return the smallest amount of memory (in bytes) which the VM system will
210   // allocate.
211   static size_t VMAllocationGranularity();
212 
213 #if BUILDFLAG(IS_CHROMEOS)
214   // Set |value| and return true if LsbRelease contains information about |key|.
215   static bool GetLsbReleaseValue(const std::string& key, std::string* value);
216 
217   // Convenience function for GetLsbReleaseValue("CHROMEOS_RELEASE_BOARD",...).
218   // Returns "unknown" if CHROMEOS_RELEASE_BOARD is not set. Otherwise, returns
219   // the full name of the board. Note that the returned value often differs
220   // between developers' systems and devices that use official builds. E.g. for
221   // a developer-built image, the function could return 'glimmer', while in an
222   // official build, it may be something like 'glimmer-signed-mp-v4keys'.
223   //
224   // NOTE: Strings returned by this function should be treated as opaque values
225   // within Chrome (e.g. for reporting metrics elsewhere). If you need to make
226   // Chrome behave differently for different Chrome OS devices, either directly
227   // check for the hardware feature that you care about (preferred) or add a
228   // command-line flag to Chrome and pass it from session_manager (based on
229   // whether a USE flag is set or not). See https://goo.gl/BbBkzg for more
230   // details.
231   static std::string GetLsbReleaseBoard();
232 
233   // Returns the creation time of /etc/lsb-release. (Used to get the date and
234   // time of the Chrome OS build).
235   static Time GetLsbReleaseTime();
236 
237   // Returns true when actually running in a Chrome OS environment.
238   static bool IsRunningOnChromeOS();
239 
240   // Overrides |lsb_release| and |lsb_release_time|. Overrides cannot be nested.
241   // Call ResetChromeOSVersionInfoForTest() to restore the previous values.
242   // Prefer base::test::ScopedChromeOSVersionInfo to calling this function.
243   static void SetChromeOSVersionInfoForTest(const std::string& lsb_release,
244                                             const Time& lsb_release_time);
245 
246   // Undoes the function above.
247   static void ResetChromeOSVersionInfoForTest();
248 
249   // Returns the kernel version of the host operating system.
250   static std::string KernelVersion();
251 
252   // Crashes if running on Chrome OS non-test image. Use only for really
253   // sensitive and risky use cases. Only works while running in verified mode,
254   // this check an easily be bypassed in dev mode.
255   static void CrashIfChromeOSNonTestImage();
256 #endif  // BUILDFLAG(IS_CHROMEOS)
257 
258 #if BUILDFLAG(IS_ANDROID)
259   // Returns the Android build's codename.
260   static std::string GetAndroidBuildCodename();
261 
262   // Returns the Android build ID.
263   static std::string GetAndroidBuildID();
264 
265   // Returns the Android hardware EGL system property.
266   static std::string GetAndroidHardwareEGL();
267 #endif  // BUILDFLAG(IS_ANDROID)
268 
269 #if BUILDFLAG(IS_IOS)
270   // Returns the iOS build number string which is normally an alphanumeric
271   // string like 12E456. This build number can differentiate between different
272   // versions of iOS that may have the same major/minor/bugfix version numbers.
273   // For example, iOS beta releases have the same version number but different
274   // build number strings.
275   static std::string GetIOSBuildNumber();
276 
277   // Overrides the hardware model name. The overridden value is used instead of
278   // `StringSysctl({CTL_HW, HW_MACHINE})`. `name` should not be empty.
279   static void OverrideHardwareModelName(std::string name);
280 #endif  // BUILDFLAG(IS_IOS)
281 
282   // Returns true for low-end devices that may require extreme tradeoffs,
283   // including user-visible changes, for acceptable performance.
284   // For general memory optimizations, consider |AmountOfPhysicalMemoryMB|.
285   //
286   // On Android this returns:
287   //   true when memory <= 1GB on Android O and later.
288   //   true when memory <= 512MB on Android N and earlier.
289   // This is not the same as "low-memory" and will be false on a large number of
290   // <=1GB pre-O Android devices. See: |detectLowEndDevice| in SysUtils.java.
291   // On Desktop this returns true when memory <= 2GB.
292   static bool IsLowEndDevice();
293 
294   // The same as IsLowEndDevice() except on Android.
295   //
296   // On Android this returns:
297   //   true when IsLowEndDevice() returns true.
298   //   true when the physical memory of the device is 4gb or 6gb and
299   //             the feature: kPartialLowEndModeOnMidEndDevices() is enabled.
300   static bool IsLowEndDeviceOrPartialLowEndModeEnabled();
301   static bool IsLowEndDeviceOrPartialLowEndModeEnabled(
302       const FeatureParam<bool>& param_for_exclusion);
303 
304 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
305   // Returns true for Android devices whose memory is X GB, considering
306   // carveouts. The carveouts is memory reserved by the system, e.g.
307   // for drivers, MTE, etc. It's very common for querying app to see
308   // hundreds MBs less than actual physical memory installed on the system.
309   // Addendum: This logic should also work for ChromeOS.
310   static bool Is3GbDevice();
311   static bool Is4GbDevice();
312   static bool Is6GbDevice();
313   // Returns true for Android devices whose memory is 4GB or 6GB, considering
314   // carveouts.
315   static bool Is4GbOr6GbDevice();
316 #endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
317 
318 #if BUILDFLAG(IS_MAC)
319   // Indicates that CPU security mitigations are enabled for the current
320   // process. This is used to control the behavior of NumberOfProcessors(), see
321   // comment on that method.
322   static void SetCpuSecurityMitigationsEnabled();
323 
324   // Resets all state associated with CPU security mitigations.
325   static void ResetCpuSecurityMitigationsEnabledForTesting();
326 #endif
327 
328  private:
329   friend class test::ScopedAmountOfPhysicalMemoryOverride;
330   FRIEND_TEST_ALL_PREFIXES(SysInfoTest, AmountOfAvailablePhysicalMemory);
331   FRIEND_TEST_ALL_PREFIXES(debug::SystemMetricsTest, ParseMeminfo);
332 
333   static int NumberOfEfficientProcessorsImpl();
334   static uint64_t AmountOfPhysicalMemoryImpl();
335   static uint64_t AmountOfAvailablePhysicalMemoryImpl();
336   static bool IsLowEndDeviceImpl();
337   static HardwareInfo GetHardwareInfoSync();
338 
339 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
340     BUILDFLAG(IS_AIX)
341   static uint64_t AmountOfAvailablePhysicalMemory(
342       const SystemMemoryInfoKB& meminfo);
343 #endif
344 
345   // Sets the amount of physical memory in MB for testing, thus allowing tests
346   // to run irrespective of the host machine's configuration.
347   static std::optional<uint64_t> SetAmountOfPhysicalMemoryMbForTesting(
348       uint64_t amount_of_memory_mb);
349   static void ClearAmountOfPhysicalMemoryMbForTesting();
350 };
351 
352 }  // namespace base
353 
354 #endif  // BASE_SYSTEM_SYS_INFO_H_
355