Re: [PATCH] tools/power/x86/turbostat: add NULL check after calloc()

From: Len Brown

Date: Thu Oct 01 2026 - 10:45:50 EST


Applied -- thanks!

Len Brown
Intel Open Source Technology Center

On Wed, Sep 2, 2026 at 2:59 AM longlong yan <yanlonglong@xxxxxxxxxx> wrote:
>
> Three calloc() calls in turbostat lack NULL return checks, leading to
> potential NULL pointer dereferences on allocation failure:
>
> 1. rapl_perf_init(): the allocated `domain_visited` is used later via
> memset(domain_visited, 0, ...) without checking for NULL.
>
> 2. added_perf_counters_init_(): the allocated `domain_visited` is used
> later via memset() and domain_visited[next_domain] without checking
> for NULL.
>
> 3. pmt_add_counter(): the allocated `pcounter` is dereferenced
> immediately via strncpy(pcounter->name, ...) without checking for
> NULL.
>
> Add NULL checks after each calloc(), using the same error handling
> style already present in each function: err(-1, ...) for rapl_perf_init(),
> errx(1, ...) for added_perf_counters_init_(), and return 1 for
> pmt_add_counter().
>
> Signed-off-by: longlong yan <yanlonglong@xxxxxxxxxx>
> ---
> tools/power/x86/turbostat/turbostat.c | 6 ++++++
> 1 file changed, 6 insertions(+)
>
> diff --git a/tools/power/x86/turbostat/turbostat.c b/tools/power/x86/turbostat/turbostat.c
> index 4ad7cb1df5c5..926dd1422fbe 100644
> --- a/tools/power/x86/turbostat/turbostat.c
> +++ b/tools/power/x86/turbostat/turbostat.c
> @@ -8578,6 +8578,8 @@ void rapl_perf_init(void)
> {
> const unsigned int num_domains = get_rapl_num_domains();
> bool *domain_visited = calloc(num_domains, sizeof(bool));
> + if (!domain_visited)
> + err(-1, "calloc domain_visited");
>
> rapl_counter_info_perdomain = calloc(num_domains, sizeof(*rapl_counter_info_perdomain));
> if (rapl_counter_info_perdomain == NULL)
> @@ -9942,6 +9944,8 @@ int added_perf_counters_init_(struct perf_counter_info *pinfo)
> const size_t max_num_domains = MAX(topo.max_cpu_num + 1, MAX(topo.max_core_id + 1, topo.max_package_id + 1));
>
> domain_visited = calloc(max_num_domains, sizeof(*domain_visited));
> + if (!domain_visited)
> + errx(1, "%s: alloc %s", __func__, "domain_visited");
>
> while (pinfo) {
> switch (pinfo->scope) {
> @@ -10333,6 +10337,8 @@ int pmt_add_counter(unsigned int guid, unsigned int seq, const char *name, enum
> pcounter = pmt_find_counter(*pmt_root, name);
> if (!pcounter) {
> pcounter = calloc(1, sizeof(*pcounter));
> + if (!pcounter)
> + return 1;
> new_counter = true;
> }
>
> --
> 2.43.0
>


--
Len Brown, Intel Open Source Technology Center