From 23751fe2525811e74f8f963668b4b0b5fc80eb54 Mon Sep 17 00:00:00 2001 From: Ondrej Sury Date: Mon, 12 Jul 2021 14:21:21 +0200 Subject: [PATCH] Cache the isc_os_ncpu() result It was discovered that on some platforms (f.e. Alpine Linux with MUSL) the result of isc_os_ncpus() call differ when called before and after we drop privileges. This commit changes the isc_os_ncpus() call to cache the result from the first call and thus always return the same value during the runtime of the named. The first call to isc_os_ncpus() is made as soon as possible on the library initalization. --- lib/isc/lib.c | 2 ++ lib/isc/os.c | 22 ++++++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/isc/lib.c b/lib/isc/lib.c index 2d6950ad63..18e3284be0 100644 --- a/lib/isc/lib.c +++ b/lib/isc/lib.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -45,6 +46,7 @@ isc__initialize(void) { isc__mem_initialize(); isc__tls_initialize(); isc__trampoline_initialize(); + (void)isc_os_ncpus(); } void diff --git a/lib/isc/os.c b/lib/isc/os.c index 5ba4481d36..6a75b60976 100644 --- a/lib/isc/os.c +++ b/lib/isc/os.c @@ -9,7 +9,12 @@ * information regarding copyright ownership. */ +#include #include +#include + +static isc_once_t ncpus_once = ISC_ONCE_INIT; +static unsigned int ncpus = 0; #ifdef HAVE_SYSCONF @@ -46,10 +51,8 @@ sysctl_ncpus(void) { } #endif /* if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTLBYNAME) */ -unsigned int -isc_os_ncpus(void) { - long ncpus = 0; - +static void +ncpus_initialize(void) { #if defined(HAVE_SYSCONF) ncpus = sysconf_ncpus(); #endif /* if defined(HAVE_SYSCONF) */ @@ -61,6 +64,13 @@ isc_os_ncpus(void) { if (ncpus <= 0) { ncpus = 1; } - - return ((unsigned int)ncpus); +} + +unsigned int +isc_os_ncpus(void) { + isc_result_t result = isc_once_do(&ncpus_once, ncpus_initialize); + RUNTIME_CHECK(result == ISC_R_SUCCESS); + INSIST(ncpus > 0); + + return (ncpus); }