rust: cpufreq: reject NULL from cpufreq_cpu_get()
Subsystems (2)
PATCH 1/1 rust: cpufreq: reject NULL from cpufreq_cpu_get()
cpufreq_cpu_get() returns either a referenced policy or NULL. PolicyCpu::from_cpu() passed its return value to from_err_ptr(), which rejects ERR_PTR values but accepts NULL.
If the lookup fails, Policy::from_raw_mut() therefore constructs a mutable reference from NULL. Dropping the resulting PolicyCpu then passes the invalid pointer to cpufreq_cpu_put(), causing an oops in kobject_put().
Reject NULL with NonNull before constructing the Policy reference. Return ENODEV instead.
A KUnit negative-control run reproduced the oops with the original conversion. The same test passed with this change. The reproducer is available on request. Validated on a VM as well.
--- rust/kernel/cpufreq.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
rust/kernel/cpufreq.rs +5 -4
@@ -14,7 +14,7 @@ cpumask, device::{Bound, Device}, devres, - error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_DEFAULT_ERROR}, + error::{code::*, from_result, to_result, Result, VTABLE_DEFAULT_ERROR}, ffi::{c_char, c_ulong}, prelude::*, types::ForeignOwnable,
@@ -29,7 +29,7 @@ marker::PhantomData, ops::{Deref, DerefMut}, pin::Pin, - ptr, + ptr::{self, NonNull}, };use macros::vtable;
@@ -687,12 +687,13 @@ fn clear_data<T: ForeignOwnable>(&mut self) -> Option<T> {impl <'a>PolicyCpu <'a> {fn from_cpu (cpu:CpuId ) ->Result <Self > {// SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU. -let ptr =from_err_ptr (unsafe { bindings::cpufreq_cpu_get (u32::from (cpu)) })?; +let ptr = +NonNull ::new (unsafe { bindings::cpufreq_cpu_get (u32::from (cpu)) }).ok_or (ENODEV )?;Ok (Self (// SAFETY: The `ptr` is guaranteed to be valid and remains valid for the lifetime of // the returned reference. -unsafe {Policy ::from_raw_mut (ptr) }, +unsafe {Policy ::from_raw_mut (ptr.as_ptr ()) }, )) } }
base-commit: 73e3f0710014fe6d4ed98cfc02292f6121db7558
Signature · 1 line
2.55.0