Coverage Report

Created: 2026-09-14 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/base/internal/sysinfo.cc
Line
Count
Source
1
// Copyright 2017 The Abseil Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include "absl/base/internal/sysinfo.h"
16
17
#include <string.h>
18
19
#include <cassert>
20
#include <cerrno>
21
#include <cstdint>
22
#include <cstdio>
23
#include <cstdlib>
24
#include <ctime>
25
#include <limits>
26
#include <thread>  // NOLINT(build/c++11)
27
#include <utility>
28
#include <vector>
29
30
#include "absl/base/attributes.h"
31
#include "absl/base/call_once.h"
32
#include "absl/base/config.h"
33
#include "absl/base/internal/raw_logging.h"
34
#include "absl/base/internal/spinlock.h"
35
#include "absl/base/internal/unscaledcycleclock.h"
36
#include "absl/base/thread_annotations.h"
37
38
#ifdef _WIN32
39
#include <windows.h>
40
#else
41
#include <fcntl.h>
42
#include <pthread.h>
43
#include <sys/stat.h>
44
#include <sys/types.h>
45
#include <unistd.h>
46
#endif
47
48
#ifdef __linux__
49
#include <sys/syscall.h>
50
#endif
51
52
#if defined(__APPLE__) || defined(__FreeBSD__)
53
#include <sys/sysctl.h>
54
#endif
55
56
#ifdef __FreeBSD__
57
#include <pthread_np.h>
58
#endif
59
60
#ifdef __NetBSD__
61
#include <lwp.h>
62
#endif
63
64
#if defined(__myriad2__)
65
#include <rtems.h>
66
#endif
67
68
#if defined(__Fuchsia__)
69
#include <zircon/process.h>
70
#endif
71
72
namespace absl {
73
ABSL_NAMESPACE_BEGIN
74
namespace base_internal {
75
76
namespace {
77
78
#if defined(_WIN32)
79
80
// Returns number of bits set in `bitMask`
81
DWORD Win32CountSetBits(ULONG_PTR bitMask) {
82
  for (DWORD bitSetCount = 0; ; ++bitSetCount) {
83
    if (bitMask == 0) return bitSetCount;
84
    bitMask &= bitMask - 1;
85
  }
86
}
87
88
// Returns the number of logical CPUs using GetLogicalProcessorInformation(), or
89
// 0 if the number of processors is not available or can not be computed.
90
// https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation
91
int Win32NumCPUs() {
92
#pragma comment(lib, "kernel32.lib")
93
  using Info = SYSTEM_LOGICAL_PROCESSOR_INFORMATION;
94
95
  DWORD info_size = sizeof(Info);
96
  Info* info(static_cast<Info*>(malloc(info_size)));
97
  if (info == nullptr) return 0;
98
99
  bool success = GetLogicalProcessorInformation(info, &info_size);
100
  if (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
101
    free(info);
102
    info = static_cast<Info*>(malloc(info_size));
103
    if (info == nullptr) return 0;
104
    success = GetLogicalProcessorInformation(info, &info_size);
105
  }
106
107
  DWORD logicalProcessorCount = 0;
108
  if (success) {
109
    Info* ptr = info;
110
    DWORD byteOffset = 0;
111
    while (byteOffset + sizeof(Info) <= info_size) {
112
      switch (ptr->Relationship) {
113
        case RelationProcessorCore:
114
          logicalProcessorCount += Win32CountSetBits(ptr->ProcessorMask);
115
          break;
116
117
        case RelationNumaNode:
118
        case RelationCache:
119
        case RelationProcessorPackage:
120
          // Ignore other entries
121
          break;
122
123
        default:
124
          // Ignore unknown entries
125
          break;
126
      }
127
      byteOffset += sizeof(Info);
128
      ptr++;
129
    }
130
  }
131
  free(info);
132
  return static_cast<int>(logicalProcessorCount);
133
}
134
135
#endif
136
137
}  // namespace
138
139
0
static int GetNumCPUs() {
140
#if defined(__myriad2__)
141
  return 1;
142
#elif defined(_WIN32)
143
  const int hardware_concurrency = Win32NumCPUs();
144
  return hardware_concurrency ? hardware_concurrency : 1;
145
#elif defined(_AIX)
146
  return sysconf(_SC_NPROCESSORS_ONLN);
147
#else
148
  // Other possibilities:
149
  //  - Read /sys/devices/system/cpu/online and use cpumask_parse()
150
  //  - sysconf(_SC_NPROCESSORS_ONLN)
151
0
  return static_cast<int>(std::thread::hardware_concurrency());
152
0
#endif
153
0
}
154
155
#if defined(_WIN32)
156
157
static double GetNominalCPUFrequency() {
158
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \
159
    !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
160
  // UWP apps don't have access to the registry and currently don't provide an
161
  // API informing about CPU nominal frequency.
162
  return 1.0;
163
#else
164
#pragma comment(lib, "advapi32.lib")  // For Reg* functions.
165
  HKEY key;
166
  // Use the Reg* functions rather than the SH functions because shlwapi.dll
167
  // pulls in gdi32.dll which makes process destruction much more costly.
168
  if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
169
                    "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
170
                    KEY_READ, &key) == ERROR_SUCCESS) {
171
    DWORD type = 0;
172
    DWORD data = 0;
173
    DWORD data_size = sizeof(data);
174
    auto result = RegQueryValueExA(key, "~MHz", nullptr, &type,
175
                                   reinterpret_cast<LPBYTE>(&data), &data_size);
176
    RegCloseKey(key);
177
    if (result == ERROR_SUCCESS && type == REG_DWORD &&
178
        data_size == sizeof(data)) {
179
      return data * 1e6;  // Value is MHz.
180
    }
181
  }
182
  return 1.0;
183
#endif  // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP
184
}
185
186
#elif defined(CTL_HW) && defined(HW_CPU_FREQ)
187
188
static double GetNominalCPUFrequency() {
189
  unsigned freq;
190
  size_t size = sizeof(freq);
191
  int mib[2] = {CTL_HW, HW_CPU_FREQ};
192
  if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) {
193
    return static_cast<double>(freq);
194
  }
195
  return 1.0;
196
}
197
198
#else
199
200
// Helper function for reading a long from a file. Returns true if successful
201
// and the memory location pointed to by value is set to the value read.
202
0
static bool ReadLongFromFile(const char *file, long *value) {
203
0
  bool ret = false;
204
0
#if defined(_POSIX_C_SOURCE)
205
0
  const int file_mode = (O_RDONLY | O_CLOEXEC);
206
#else
207
  const int file_mode = O_RDONLY;
208
#endif
209
210
0
  int fd = open(file, file_mode);
211
0
  if (fd != -1) {
212
0
    char line[1024];
213
0
    char *err;
214
0
    memset(line, '\0', sizeof(line));
215
0
    ssize_t len;
216
0
    do {
217
0
      len = read(fd, line, sizeof(line) - 1);
218
0
    } while (len < 0 && errno == EINTR);
219
0
    if (len <= 0) {
220
0
      ret = false;
221
0
    } else {
222
0
      const long temp_value = strtol(line, &err, 10);
223
0
      if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
224
0
        *value = temp_value;
225
0
        ret = true;
226
0
      }
227
0
    }
228
0
    close(fd);
229
0
  }
230
0
  return ret;
231
0
}
232
233
#if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY)
234
235
// Reads a monotonic time source and returns a value in
236
// nanoseconds. The returned value uses an arbitrary epoch, not the
237
// Unix epoch.
238
0
static int64_t ReadMonotonicClockNanos() {
239
0
  struct timespec t;
240
0
#ifdef CLOCK_MONOTONIC_RAW
241
0
  int rc = clock_gettime(CLOCK_MONOTONIC_RAW, &t);
242
#else
243
  int rc = clock_gettime(CLOCK_MONOTONIC, &t);
244
#endif
245
0
  if (rc != 0) {
246
0
    ABSL_RAW_LOG(FATAL, "clock_gettime() failed: (%d)", errno);
247
0
  }
248
0
  return int64_t{t.tv_sec} * 1000000000 + t.tv_nsec;
249
0
}
250
251
class UnscaledCycleClockWrapperForInitializeFrequency {
252
 public:
253
0
  static int64_t Now() { return base_internal::UnscaledCycleClock::Now(); }
254
};
255
256
struct TimeTscPair {
257
  int64_t time;  // From ReadMonotonicClockNanos().
258
  int64_t tsc;   // From UnscaledCycleClock::Now().
259
};
260
261
// Returns a pair of values (monotonic kernel time, TSC ticks) that
262
// approximately correspond to each other.  This is accomplished by
263
// doing several reads and picking the reading with the lowest
264
// latency.  This approach is used to minimize the probability that
265
// our thread was preempted between clock reads.
266
0
static TimeTscPair GetTimeTscPair() {
267
0
  int64_t best_latency = std::numeric_limits<int64_t>::max();
268
0
  TimeTscPair best;
269
0
  for (int i = 0; i < 10; ++i) {
270
0
    int64_t t0 = ReadMonotonicClockNanos();
271
0
    int64_t tsc = UnscaledCycleClockWrapperForInitializeFrequency::Now();
272
0
    int64_t t1 = ReadMonotonicClockNanos();
273
0
    int64_t latency = t1 - t0;
274
0
    if (latency < best_latency) {
275
0
      best_latency = latency;
276
0
      best.time = t0;
277
0
      best.tsc = tsc;
278
0
    }
279
0
  }
280
0
  return best;
281
0
}
282
283
// Measures and returns the TSC frequency by taking a pair of
284
// measurements approximately `sleep_nanoseconds` apart.
285
0
static double MeasureTscFrequencyWithSleep(int sleep_nanoseconds) {
286
0
  auto t0 = GetTimeTscPair();
287
0
  struct timespec ts;
288
0
  ts.tv_sec = 0;
289
0
  ts.tv_nsec = sleep_nanoseconds;
290
0
  while (nanosleep(&ts, &ts) != 0 && errno == EINTR) {}
291
0
  auto t1 = GetTimeTscPair();
292
0
  double elapsed_ticks = t1.tsc - t0.tsc;
293
0
  double elapsed_time = (t1.time - t0.time) * 1e-9;
294
0
  return elapsed_ticks / elapsed_time;
295
0
}
296
297
// Measures and returns the TSC frequency by calling
298
// MeasureTscFrequencyWithSleep(), doubling the sleep interval until the
299
// frequency measurement stabilizes.
300
0
static double MeasureTscFrequency() {
301
0
  double last_measurement = -1.0;
302
0
  int sleep_nanoseconds = 1000000;  // 1 millisecond.
303
0
  for (int i = 0; i < 8; ++i) {
304
0
    double measurement = MeasureTscFrequencyWithSleep(sleep_nanoseconds);
305
0
    if (measurement * 0.99 < last_measurement &&
306
0
        last_measurement < measurement * 1.01) {
307
      // Use the current measurement if it is within 1% of the
308
      // previous measurement.
309
0
      return measurement;
310
0
    }
311
0
    last_measurement = measurement;
312
0
    sleep_nanoseconds *= 2;
313
0
  }
314
0
  return last_measurement;
315
0
}
316
317
#endif  // ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY
318
319
0
static double GetNominalCPUFrequency() {
320
0
  long freq = 0;
321
322
  // Google's production kernel has a patch to export the TSC
323
  // frequency through sysfs. If the kernel is exporting the TSC
324
  // frequency use that. There are issues where cpuinfo_max_freq
325
  // cannot be relied on because the BIOS may be exporting an invalid
326
  // p-state (on x86) or p-states may be used to put the processor in
327
  // a new mode (turbo mode). Essentially, those frequencies cannot
328
  // always be relied upon. The same reasons apply to /proc/cpuinfo as
329
  // well.
330
0
  if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq)) {
331
0
    return freq * 1e3;  // Value is kHz.
332
0
  }
333
334
0
#if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY)
335
  // On these platforms, the TSC frequency is the nominal CPU
336
  // frequency.  But without having the kernel export it directly
337
  // though /sys/devices/system/cpu/cpu0/tsc_freq_khz, there is no
338
  // other way to reliably get the TSC frequency, so we have to
339
  // measure it ourselves.  Some CPUs abuse cpuinfo_max_freq by
340
  // exporting "fake" frequencies for implementing new features. For
341
  // example, Intel's turbo mode is enabled by exposing a p-state
342
  // value with a higher frequency than that of the real TSC
343
  // rate. Because of this, we prefer to measure the TSC rate
344
  // ourselves on i386 and x86-64.
345
0
  return MeasureTscFrequency();
346
#else
347
348
  // If CPU scaling is in effect, we want to use the *maximum*
349
  // frequency, not whatever CPU speed some random processor happens
350
  // to be using now.
351
  if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
352
                       &freq)) {
353
    return freq * 1e3;  // Value is kHz.
354
  }
355
356
  return 1.0;
357
#endif  // !ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY
358
0
}
359
360
#endif
361
362
ABSL_CONST_INIT static once_flag init_num_cpus_once;
363
ABSL_CONST_INIT static int num_cpus = 0;
364
365
// NumCPUs() may be called before main() and before malloc is properly
366
// initialized, therefore this must not allocate memory.
367
0
int NumCPUs() {
368
0
  base_internal::LowLevelCallOnce(
369
0
      &init_num_cpus_once, []() { num_cpus = GetNumCPUs(); });
370
0
  return num_cpus;
371
0
}
372
373
// A default frequency of 0.0 might be dangerous if it is used in division.
374
ABSL_CONST_INIT static once_flag init_nominal_cpu_frequency_once;
375
ABSL_CONST_INIT static double nominal_cpu_frequency = 1.0;
376
377
// NominalCPUFrequency() may be called before main() and before malloc is
378
// properly initialized, therefore this must not allocate memory.
379
0
double NominalCPUFrequency() {
380
0
  base_internal::LowLevelCallOnce(&init_nominal_cpu_frequency_once, []() {
381
0
    nominal_cpu_frequency = GetNominalCPUFrequency();
382
0
  });
383
0
  return nominal_cpu_frequency;
384
0
}
385
386
#if defined(_WIN32)
387
388
pid_t GetTID() { return pid_t{GetCurrentThreadId()}; }
389
390
#elif defined(__linux__)
391
#ifdef __ANDROID__
392
#if __ANDROID_API__ >= 21
393
#define ABSL_INTERNAL_HAVE_GETTID 1
394
#endif
395
#endif
396
397
#ifdef ABSL_INTERNAL_HAVE_GETTID
398
pid_t GetTID() {
399
  return static_cast<pid_t>(gettid());
400
}
401
#else
402
#ifndef SYS_gettid
403
#define SYS_gettid __NR_gettid
404
#endif
405
406
0
pid_t GetTID() { return static_cast<pid_t>(syscall(SYS_gettid)); }
407
408
#endif
409
#undef ABSL_INTERNAL_HAVE_GETTID
410
#elif defined(__akaros__)
411
412
pid_t GetTID() {
413
  // Akaros has a concept of "vcore context", which is the state the program
414
  // is forced into when we need to make a user-level scheduling decision, or
415
  // run a signal handler.  This is analogous to the interrupt context that a
416
  // CPU might enter if it encounters some kind of exception.
417
  //
418
  // There is no current thread context in vcore context, but we need to give
419
  // a reasonable answer if asked for a thread ID (e.g., in a signal handler).
420
  // Thread 0 always exists, so if we are in vcore context, we return that.
421
  //
422
  // Otherwise, we know (since we are using pthreads) that the uthread struct
423
  // current_uthread is pointing to is the first element of a
424
  // struct pthread_tcb, so we extract and return the thread ID from that.
425
  //
426
  // TODO(dcross): Akaros anticipates moving the thread ID to the uthread
427
  // structure at some point. We should modify this code to remove the cast
428
  // when that happens.
429
  if (in_vcore_context()) return 0;
430
  return reinterpret_cast<struct pthread_tcb*>(current_uthread)->id;
431
}
432
433
#elif defined(__myriad2__)
434
435
pid_t GetTID() {
436
  uint32_t tid;
437
  rtems_task_ident(RTEMS_SELF, 0, &tid);
438
  return tid;
439
}
440
441
#elif defined(__APPLE__)
442
443
pid_t GetTID() {
444
  uint64_t tid;
445
  // `nullptr` here implies this thread.  This only fails if the specified
446
  // thread is invalid or the pointer-to-tid is null, so we needn't worry about
447
  // it.
448
  pthread_threadid_np(nullptr, &tid);
449
  return static_cast<pid_t>(tid);
450
}
451
452
#elif defined(__FreeBSD__)
453
454
pid_t GetTID() { return static_cast<pid_t>(pthread_getthreadid_np()); }
455
456
#elif defined(__OpenBSD__)
457
458
pid_t GetTID() { return getthrid(); }
459
460
#elif defined(__NetBSD__)
461
462
pid_t GetTID() { return static_cast<pid_t>(_lwp_self()); }
463
464
#elif defined(__Fuchsia__)
465
466
pid_t GetTID() {
467
  // Use our thread handle as the TID, which should be unique within this
468
  // process (but may not be globally unique). The handle value was chosen over
469
  // a kernel object ID (KOID) because zx_handle_t (32-bits) can be cast to a
470
  // pid_t type without loss of precision, but a zx_koid_t (64-bits) cannot.
471
  return static_cast<pid_t>(zx_thread_self());
472
}
473
474
#else
475
476
// Fallback implementation of `GetTID` using `pthread_self`.
477
pid_t GetTID() {
478
  // `pthread_t` need not be arithmetic per POSIX; platforms where it isn't
479
  // should be handled above.
480
  return static_cast<pid_t>(pthread_self());
481
}
482
483
#endif
484
485
// GetCachedTID() caches the thread ID in thread-local storage (which is a
486
// userspace construct) to avoid unnecessary system calls. Without this caching,
487
// it can take roughly 98ns, while it takes roughly 1ns with this caching.
488
0
pid_t GetCachedTID() {
489
#ifdef __ANDROID__
490
// NDK defaults to emulated TLS for API < 29, and native ELF TLS for API >= 29.
491
// Emulated TLS is slower than bionic's internal caching.
492
#if __ANDROID_API__ < 29
493
#define ABSL_INTERNAL_USING_EMULATED_TLS 1
494
#endif
495
#endif
496
497
0
#if defined(ABSL_HAVE_THREAD_LOCAL) && \
498
0
    !defined(ABSL_INTERNAL_USING_EMULATED_TLS)
499
0
  static thread_local pid_t thread_id = GetTID();
500
0
  return thread_id;
501
#else
502
  return GetTID();
503
#endif  // defined(ABSL_HAVE_THREAD_LOCAL) &&
504
        // !defined(ABSL_INTERNAL_USING_EMULATED_TLS)
505
0
#undef ABSL_INTERNAL_USING_EMULATED_TLS
506
0
}
507
508
}  // namespace base_internal
509
ABSL_NAMESPACE_END
510
}  // namespace absl