Skip to contentSkip to conversation

cpupower: Fix NULL pointer dereference on allocation failure

PATCH In review Malaya Kumar Rout 2 participants 2 messages Jul 4 – Jul 16 CPU power monitoring

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 cpupower: Fix NULL pointer dereference on allocation failure

The bitmask_alloc() function can return NULL if memory allocation fails, but the code in main() does not check the return values before using the allocated bitmasks. This can lead to a NULL pointer dereference when bitmask_setall() or bitmask_parselist() is called with NULL pointers.

Add proper NULL checks after bitmask allocations and exit gracefully with an error message if allocation fails.

Fixes 748f0d70087c ("cpupower: Provide online and offline CPU information")
---
 tools/power/cpupower/utils/cpupower.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
tools/power/cpupower/utils/cpupower.c +11 -0
index 9ec973165af1..8f7b18b8bb43 100644
@@ -184,6 +184,17 @@ int main(int argc, const char *argv[])
 	online_cpus = bitmask_alloc(sysconf(_SC_NPROCESSORS_CONF));
 	offline_cpus = bitmask_alloc(sysconf(_SC_NPROCESSORS_CONF));
 
+	if (!cpus_chosen || !online_cpus || !offline_cpus) {
+		fprintf(stderr, _("Failed to allocate bitmasks\n"));
+		if (cpus_chosen)
+			bitmask_free(cpus_chosen);
+		if (online_cpus)
+			bitmask_free(online_cpus);
+		if (offline_cpus)
+			bitmask_free(offline_cpus);
+		return EXIT_FAILURE;
+	}
+
 	argc--;
 	argv += 1;
 
Signature · 1 line
2.54.0
maintainer
#1 lore raw
Quoted 26 lines · Malaya Kumar Rout

The bitmask_alloc() function can return NULL if memory allocation fails, but the code in main() does not check the return values before using the allocated bitmasks. This can lead to a NULL pointer dereference when bitmask_setall() or bitmask_parselist() is called with NULL pointers.

Add proper NULL checks after bitmask allocations and exit gracefully with an error message if allocation fails.

Fixes 748f0d70087c ("cpupower: Provide online and offline CPU information")
---
  tools/power/cpupower/utils/cpupower.c | 11 +++++++++++
  1 file changed, 11 insertions(+)
tools/power/cpupower/utils/cpupower.c +4 -0
index 9ec973165af1..8f7b18b8bb43 100644
@@ -184,6 +184,17 @@ int main(int argc, const char *argv[])
  	online_cpus = bitmask_alloc(sysconf(_SC_NPROCESSORS_CONF));
  	offline_cpus = bitmask_alloc(sysconf(_SC_NPROCESSORS_CONF));
 
+	if (!cpus_chosen || !online_cpus || !offline_cpus) {
+		fprintf(stderr, _("Failed to allocate bitmasks\n"));
+		if (cpus_chosen)
+			bitmask_free(cpus_chosen);

tools/power/cpupower/utils/cpupower.c int main(int argc, const char *argv[]) · line 200

Quoted 10 lines
tools/power/cpupower/utils/cpupower.c +7 -0
+		if (online_cpus)
+			bitmask_free(online_cpus);
+		if (offline_cpus)
+			bitmask_free(offline_cpus);
+		return EXIT_FAILURE;
+	}
+
  	argc--;
  	argv += 1;
 

Usually these small allocations don't fail to warrant checks.

thanks,
-- Shuah