From a8cf3b7cbd265856797526d391cf951019a2a66b Mon Sep 17 00:00:00 2001 From: Mirko Bonadei Date: Fri, 24 May 2019 13:47:23 +0200 Subject: [PATCH] Ensure CpuInfo::DetectNumberOfCores is > 0 and thread safe. This CL adds error handling for sysconf, which can return -1 and adds an RTC_CHECK_GT to ensure the value returned is always greater than 0. On top of that CpuInfo::DetectNumberOfCores is made thread safe because the static local variable is initialized with the right values istead of 0. Bug: None Change-Id: I294684e7380b12cda55ec8d6c7a90e132dc3af85 Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/138210 Commit-Queue: Mirko Bonadei Reviewed-by: Niels Moller Cr-Commit-Position: refs/heads/master@{#28057} --- system_wrappers/source/cpu_info.cc | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/system_wrappers/source/cpu_info.cc b/system_wrappers/source/cpu_info.cc index 6bcdd5f94f..7288c67efd 100644 --- a/system_wrappers/source/cpu_info.cc +++ b/system_wrappers/source/cpu_info.cc @@ -24,8 +24,7 @@ namespace internal { static int DetectNumberOfCores() { - // We fall back on assuming a single core in case of errors. - int number_of_cores = 1; + int number_of_cores; #if defined(WEBRTC_WIN) SYSTEM_INFO si; @@ -33,6 +32,10 @@ static int DetectNumberOfCores() { number_of_cores = static_cast(si.dwNumberOfProcessors); #elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID) number_of_cores = static_cast(sysconf(_SC_NPROCESSORS_ONLN)); + if (number_of_cores < 0) { + RTC_LOG(LS_ERROR) << "Failed to get number of cores"; + number_of_cores = 1; + } #elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS) int name[] = {CTL_HW, HW_AVAILCPU}; size_t size = sizeof(number_of_cores); @@ -44,10 +47,12 @@ static int DetectNumberOfCores() { number_of_cores = zx_system_get_num_cpus(); #else RTC_LOG(LS_ERROR) << "No function to get number of cores"; + number_of_cores = 1; #endif RTC_LOG(LS_INFO) << "Available number of cores: " << number_of_cores; + RTC_CHECK_GT(number_of_cores, 0); return number_of_cores; } } // namespace internal @@ -59,9 +64,8 @@ uint32_t CpuInfo::DetectNumberOfCores() { // is running in a sandbox, we may only be able to read the value once (before // the sandbox is initialized) and not thereafter. // For more information see crbug.com/176522. - static uint32_t logical_cpus = 0; - if (!logical_cpus) - logical_cpus = static_cast(internal::DetectNumberOfCores()); + static const uint32_t logical_cpus = + static_cast(internal::DetectNumberOfCores()); return logical_cpus; }