Skip to content

Commit 7f7c96a

Browse files
authored
sysinfo.cc: Always abort on GetNumCPUs failure (#1756)
Defines a wrapper function, CheckNumCPUs, which enforces that GetNumCPUs never returns fewer than one CPU. There is no reasonable way to continue if we are unable to identify the number of CPUs. Signed-off-by: Sam James <sam@gentoo.org>
1 parent 385033b commit 7f7c96a

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

src/sysinfo.cc

+17-11
Original file line numberDiff line numberDiff line change
@@ -474,12 +474,11 @@ std::string GetSystemName() {
474474
#endif // Catch-all POSIX block.
475475
}
476476

477-
int GetNumCPUs() {
477+
int GetNumCPUsImpl() {
478478
#ifdef BENCHMARK_HAS_SYSCTL
479479
int num_cpu = -1;
480480
if (GetSysctl("hw.ncpu", &num_cpu)) return num_cpu;
481-
fprintf(stderr, "Err: %s\n", strerror(errno));
482-
std::exit(EXIT_FAILURE);
481+
PrintErrorAndDie("Err: ", strerror(errno));
483482
#elif defined(BENCHMARK_OS_WINDOWS)
484483
SYSTEM_INFO sysinfo;
485484
// Use memset as opposed to = {} to avoid GCC missing initializer false
@@ -493,8 +492,8 @@ int GetNumCPUs() {
493492
// Returns -1 in case of a failure.
494493
long num_cpu = sysconf(_SC_NPROCESSORS_ONLN);
495494
if (num_cpu < 0) {
496-
fprintf(stderr, "sysconf(_SC_NPROCESSORS_ONLN) failed with error: %s\n",
497-
strerror(errno));
495+
PrintErrorAndDie("sysconf(_SC_NPROCESSORS_ONLN) failed with error: ",
496+
strerror(errno));
498497
}
499498
return (int)num_cpu;
500499
#elif defined(BENCHMARK_OS_QNX)
@@ -510,8 +509,7 @@ int GetNumCPUs() {
510509
int max_id = -1;
511510
std::ifstream f("/proc/cpuinfo");
512511
if (!f.is_open()) {
513-
std::cerr << "failed to open /proc/cpuinfo\n";
514-
return -1;
512+
PrintErrorAndDie("Failed to open /proc/cpuinfo");
515513
}
516514
#if defined(__alpha__)
517515
const std::string Key = "cpus detected";
@@ -540,12 +538,10 @@ int GetNumCPUs() {
540538
}
541539
}
542540
if (f.bad()) {
543-
std::cerr << "Failure reading /proc/cpuinfo\n";
544-
return -1;
541+
PrintErrorAndDie("Failure reading /proc/cpuinfo");
545542
}
546543
if (!f.eof()) {
547-
std::cerr << "Failed to read to end of /proc/cpuinfo\n";
548-
return -1;
544+
PrintErrorAndDie("Failed to read to end of /proc/cpuinfo");
549545
}
550546
f.close();
551547

@@ -559,6 +555,16 @@ int GetNumCPUs() {
559555
BENCHMARK_UNREACHABLE();
560556
}
561557

558+
int GetNumCPUs() {
559+
const int num_cpus = GetNumCPUsImpl();
560+
if (num_cpus < 1) {
561+
PrintErrorAndDie(
562+
"Unable to extract number of CPUs. If your platform uses "
563+
"/proc/cpuinfo, custom support may need to be added.");
564+
}
565+
return num_cpus;
566+
}
567+
562568
class ThreadAffinityGuard final {
563569
public:
564570
ThreadAffinityGuard() : reset_affinity(SetAffinity()) {

0 commit comments

Comments
 (0)