Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit cae4454

Browse files
authoredJun 4, 2021
Merge pull request #348 from ojeda/warnings
Clean `unsafe` in `unsafe fn`s warnings
2 parents 0b9bcdf + a0ea20f commit cae4454

21 files changed

+114
-98
lines changed
 

‎Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -516,7 +516,7 @@ KBUILD_RUSTCFLAGS := --emit=dep-info,obj,metadata --edition=2018 \
516516
-Cpanic=abort -Cembed-bitcode=n -Clto=n -Crpath=n \
517517
-Cforce-unwind-tables=n -Ccodegen-units=1 \
518518
-Zbinary_dep_depinfo=y -Zsymbol-mangling-version=v0 \
519-
-W unsafe_op_in_unsafe_fn
519+
-D unsafe_op_in_unsafe_fn
520520
KBUILD_AFLAGS_KERNEL :=
521521
KBUILD_CFLAGS_KERNEL :=
522522
KBUILD_RUSTCFLAGS_KERNEL :=

‎drivers/android/node.rs

+8-6
Original file line numberDiff line numberDiff line change
@@ -83,12 +83,14 @@ impl NodeDeath {
8383
cookie,
8484
work_links: Links::new(),
8585
death_links: Links::new(),
86-
inner: SpinLock::new(NodeDeathInner {
87-
dead: false,
88-
cleared: false,
89-
notification_done: false,
90-
aborted: false,
91-
}),
86+
inner: unsafe {
87+
SpinLock::new(NodeDeathInner {
88+
dead: false,
89+
cleared: false,
90+
notification_done: false,
91+
aborted: false,
92+
})
93+
},
9294
}
9395
}
9496

‎rust/kernel/allocator.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@ unsafe impl GlobalAlloc for KernelAllocator {
1414
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
1515
// `krealloc()` is used instead of `kmalloc()` because the latter is
1616
// an inline function and cannot be bound to as a result.
17-
bindings::krealloc(ptr::null(), layout.size(), bindings::GFP_KERNEL) as *mut u8
17+
unsafe { bindings::krealloc(ptr::null(), layout.size(), bindings::GFP_KERNEL) as *mut u8 }
1818
}
1919

2020
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
21-
bindings::kfree(ptr as *const c_types::c_void);
21+
unsafe {
22+
bindings::kfree(ptr as *const c_types::c_void);
23+
}
2224
}
2325
}
2426

‎rust/kernel/bindings.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
non_camel_case_types,
1010
non_upper_case_globals,
1111
non_snake_case,
12-
improper_ctypes
12+
improper_ctypes,
13+
unsafe_op_in_unsafe_fn
1314
)]
1415
mod bindings_raw {
1516
use crate::c_types;

‎rust/kernel/file_operations.rs

+43-39
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,10 @@ impl PollTable {
5757

5858
// SAFETY: `PollTable::ptr` is guaranteed to be valid by the type invariants and the null
5959
// check above.
60-
let table = &*self.ptr;
60+
let table = unsafe { &*self.ptr };
6161
if let Some(proc) = table._qproc {
6262
// SAFETY: All pointers are known to be valid.
63-
proc(file.ptr as _, cv.wait_list.get(), self.ptr)
63+
unsafe { proc(file.ptr as _, cv.wait_list.get(), self.ptr) }
6464
}
6565
}
6666
}
@@ -84,9 +84,9 @@ unsafe extern "C" fn open_callback<A: FileOpenAdapter, T: FileOpener<A::Arg>>(
8484
file: *mut bindings::file,
8585
) -> c_types::c_int {
8686
from_kernel_result! {
87-
let arg = A::convert(inode, file);
88-
let ptr = T::open(&*arg)?.into_pointer();
89-
(*file).private_data = ptr as *mut c_types::c_void;
87+
let arg = unsafe { A::convert(inode, file) };
88+
let ptr = T::open(unsafe { &*arg })?.into_pointer();
89+
unsafe { (*file).private_data = ptr as *mut c_types::c_void };
9090
Ok(0)
9191
}
9292
}
@@ -98,12 +98,12 @@ unsafe extern "C" fn read_callback<T: FileOperations>(
9898
offset: *mut bindings::loff_t,
9999
) -> c_types::c_ssize_t {
100100
from_kernel_result! {
101-
let mut data = UserSlicePtr::new(buf as *mut c_types::c_void, len).writer();
102-
let f = &*((*file).private_data as *const T);
101+
let mut data = unsafe { UserSlicePtr::new(buf as *mut c_types::c_void, len).writer() };
102+
let f = unsafe { &*((*file).private_data as *const T) };
103103
// No `FMODE_UNSIGNED_OFFSET` support, so `offset` must be in [0, 2^63).
104104
// See discussion in https://github.com/fishinabarrel/linux-kernel-module-rust/pull/113
105-
let read = f.read(&FileRef::from_ptr(file), &mut data, (*offset).try_into()?)?;
106-
(*offset) += bindings::loff_t::try_from(read).unwrap();
105+
let read = f.read(unsafe { &FileRef::from_ptr(file) }, &mut data, unsafe { *offset }.try_into()?)?;
106+
unsafe { (*offset) += bindings::loff_t::try_from(read).unwrap() };
107107
Ok(read as _)
108108
}
109109
}
@@ -113,12 +113,12 @@ unsafe extern "C" fn read_iter_callback<T: FileOperations>(
113113
raw_iter: *mut bindings::iov_iter,
114114
) -> isize {
115115
from_kernel_result! {
116-
let mut iter = IovIter::from_ptr(raw_iter);
117-
let file = (*iocb).ki_filp;
118-
let offset = (*iocb).ki_pos;
119-
let f = &*((*file).private_data as *const T);
120-
let read = f.read(&FileRef::from_ptr(file), &mut iter, offset.try_into()?)?;
121-
(*iocb).ki_pos += bindings::loff_t::try_from(read).unwrap();
116+
let mut iter = unsafe { IovIter::from_ptr(raw_iter) };
117+
let file = unsafe { (*iocb).ki_filp };
118+
let offset = unsafe { (*iocb).ki_pos };
119+
let f = unsafe { &*((*file).private_data as *const T) };
120+
let read = f.read(unsafe { &FileRef::from_ptr(file) }, &mut iter, offset.try_into()?)?;
121+
unsafe { (*iocb).ki_pos += bindings::loff_t::try_from(read).unwrap() };
122122
Ok(read as _)
123123
}
124124
}
@@ -130,12 +130,12 @@ unsafe extern "C" fn write_callback<T: FileOperations>(
130130
offset: *mut bindings::loff_t,
131131
) -> c_types::c_ssize_t {
132132
from_kernel_result! {
133-
let mut data = UserSlicePtr::new(buf as *mut c_types::c_void, len).reader();
134-
let f = &*((*file).private_data as *const T);
133+
let mut data = unsafe { UserSlicePtr::new(buf as *mut c_types::c_void, len).reader() };
134+
let f = unsafe { &*((*file).private_data as *const T) };
135135
// No `FMODE_UNSIGNED_OFFSET` support, so `offset` must be in [0, 2^63).
136136
// See discussion in https://github.com/fishinabarrel/linux-kernel-module-rust/pull/113
137-
let written = f.write(&FileRef::from_ptr(file), &mut data, (*offset).try_into()?)?;
138-
(*offset) += bindings::loff_t::try_from(written).unwrap();
137+
let written = f.write(unsafe { &FileRef::from_ptr(file) }, &mut data, unsafe { *offset }.try_into()?)?;
138+
unsafe { (*offset) += bindings::loff_t::try_from(written).unwrap() };
139139
Ok(written as _)
140140
}
141141
}
@@ -145,12 +145,12 @@ unsafe extern "C" fn write_iter_callback<T: FileOperations>(
145145
raw_iter: *mut bindings::iov_iter,
146146
) -> isize {
147147
from_kernel_result! {
148-
let mut iter = IovIter::from_ptr(raw_iter);
149-
let file = (*iocb).ki_filp;
150-
let offset = (*iocb).ki_pos;
151-
let f = &*((*file).private_data as *const T);
152-
let written = f.write(&FileRef::from_ptr(file), &mut iter, offset.try_into()?)?;
153-
(*iocb).ki_pos += bindings::loff_t::try_from(written).unwrap();
148+
let mut iter = unsafe { IovIter::from_ptr(raw_iter) };
149+
let file = unsafe { (*iocb).ki_filp };
150+
let offset = unsafe { (*iocb).ki_pos };
151+
let f = unsafe { &*((*file).private_data as *const T) };
152+
let written = f.write(unsafe { &FileRef::from_ptr(file) }, &mut iter, offset.try_into()?)?;
153+
unsafe { (*iocb).ki_pos += bindings::loff_t::try_from(written).unwrap() };
154154
Ok(written as _)
155155
}
156156
}
@@ -159,8 +159,10 @@ unsafe extern "C" fn release_callback<T: FileOperations>(
159159
_inode: *mut bindings::inode,
160160
file: *mut bindings::file,
161161
) -> c_types::c_int {
162-
let ptr = mem::replace(&mut (*file).private_data, ptr::null_mut());
163-
T::release(T::Wrapper::from_pointer(ptr as _), &FileRef::from_ptr(file));
162+
let ptr = mem::replace(unsafe { &mut (*file).private_data }, ptr::null_mut());
163+
T::release(unsafe { T::Wrapper::from_pointer(ptr as _) }, unsafe {
164+
&FileRef::from_ptr(file)
165+
});
164166
0
165167
}
166168

@@ -176,8 +178,8 @@ unsafe extern "C" fn llseek_callback<T: FileOperations>(
176178
bindings::SEEK_END => SeekFrom::End(offset),
177179
_ => return Err(Error::EINVAL),
178180
};
179-
let f = &*((*file).private_data as *const T);
180-
let off = f.seek(&FileRef::from_ptr(file), off)?;
181+
let f = unsafe { &*((*file).private_data as *const T) };
182+
let off = f.seek(unsafe { &FileRef::from_ptr(file) }, off)?;
181183
Ok(off as bindings::loff_t)
182184
}
183185
}
@@ -188,10 +190,10 @@ unsafe extern "C" fn unlocked_ioctl_callback<T: FileOperations>(
188190
arg: c_types::c_ulong,
189191
) -> c_types::c_long {
190192
from_kernel_result! {
191-
let f = &*((*file).private_data as *const T);
193+
let f = unsafe { &*((*file).private_data as *const T) };
192194
// SAFETY: This function is called by the kernel, so it must set `fs` appropriately.
193195
let mut cmd = IoctlCommand::new(cmd as _, arg as _);
194-
let ret = f.ioctl(&FileRef::from_ptr(file), &mut cmd)?;
196+
let ret = f.ioctl(unsafe { &FileRef::from_ptr(file) }, &mut cmd)?;
195197
Ok(ret as _)
196198
}
197199
}
@@ -202,10 +204,10 @@ unsafe extern "C" fn compat_ioctl_callback<T: FileOperations>(
202204
arg: c_types::c_ulong,
203205
) -> c_types::c_long {
204206
from_kernel_result! {
205-
let f = &*((*file).private_data as *const T);
207+
let f = unsafe { &*((*file).private_data as *const T) };
206208
// SAFETY: This function is called by the kernel, so it must set `fs` appropriately.
207209
let mut cmd = IoctlCommand::new(cmd as _, arg as _);
208-
let ret = f.compat_ioctl(&FileRef::from_ptr(file), &mut cmd)?;
210+
let ret = f.compat_ioctl(unsafe { &FileRef::from_ptr(file) }, &mut cmd)?;
209211
Ok(ret as _)
210212
}
211213
}
@@ -215,8 +217,8 @@ unsafe extern "C" fn mmap_callback<T: FileOperations>(
215217
vma: *mut bindings::vm_area_struct,
216218
) -> c_types::c_int {
217219
from_kernel_result! {
218-
let f = &*((*file).private_data as *const T);
219-
f.mmap(&FileRef::from_ptr(file), &mut *vma)?;
220+
let f = unsafe { &*((*file).private_data as *const T) };
221+
f.mmap(unsafe { &FileRef::from_ptr(file) }, unsafe { &mut *vma })?;
220222
Ok(0)
221223
}
222224
}
@@ -231,8 +233,8 @@ unsafe extern "C" fn fsync_callback<T: FileOperations>(
231233
let start = start.try_into()?;
232234
let end = end.try_into()?;
233235
let datasync = datasync != 0;
234-
let f = &*((*file).private_data as *const T);
235-
let res = f.fsync(&FileRef::from_ptr(file), start, end, datasync)?;
236+
let f = unsafe { &*((*file).private_data as *const T) };
237+
let res = f.fsync(unsafe { &FileRef::from_ptr(file) }, start, end, datasync)?;
236238
Ok(res.try_into().unwrap())
237239
}
238240
}
@@ -241,8 +243,10 @@ unsafe extern "C" fn poll_callback<T: FileOperations>(
241243
file: *mut bindings::file,
242244
wait: *mut bindings::poll_table_struct,
243245
) -> bindings::__poll_t {
244-
let f = &*((*file).private_data as *const T);
245-
match f.poll(&FileRef::from_ptr(file), &PollTable::from_ptr(wait)) {
246+
let f = unsafe { &*((*file).private_data as *const T) };
247+
match f.poll(unsafe { &FileRef::from_ptr(file) }, unsafe {
248+
&PollTable::from_ptr(wait)
249+
}) {
246250
Ok(v) => v,
247251
Err(_) => bindings::POLLERR,
248252
}

‎rust/kernel/iov_iter.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ impl IoBufferWriter for IovIter {
7070
}
7171

7272
unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> Result {
73-
let res = rust_helper_copy_to_iter(data as _, len, self.ptr);
73+
let res = unsafe { rust_helper_copy_to_iter(data as _, len, self.ptr) };
7474
if res != len {
7575
Err(Error::EFAULT)
7676
} else {
@@ -85,7 +85,7 @@ impl IoBufferReader for IovIter {
8585
}
8686

8787
unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result {
88-
let res = rust_helper_copy_from_iter(out as _, len, self.ptr);
88+
let res = unsafe { rust_helper_copy_from_iter(out as _, len, self.ptr) };
8989
if res != len {
9090
Err(Error::EFAULT)
9191
} else {

‎rust/kernel/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ macro_rules! offset_of {
210210
macro_rules! container_of {
211211
($ptr:expr, $type:ty, $($f:tt)*) => {{
212212
let offset = $crate::offset_of!($type, $($f)*);
213-
($ptr as *const _ as *const u8).offset(-offset) as *const $type
213+
unsafe { ($ptr as *const _ as *const u8).offset(-offset) as *const $type }
214214
}}
215215
}
216216

‎rust/kernel/linked_list.rs

+8-8
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ impl<T: ?Sized> Wrapper<T> for Box<T> {
3333
}
3434

3535
unsafe fn from_pointer(ptr: NonNull<T>) -> Self {
36-
Box::from_raw(ptr.as_ptr())
36+
unsafe { Box::from_raw(ptr.as_ptr()) }
3737
}
3838

3939
fn as_ref(&self) -> &T {
@@ -47,7 +47,7 @@ impl<T: ?Sized> Wrapper<T> for Arc<T> {
4747
}
4848

4949
unsafe fn from_pointer(ptr: NonNull<T>) -> Self {
50-
Arc::from_raw(ptr.as_ptr())
50+
unsafe { Arc::from_raw(ptr.as_ptr()) }
5151
}
5252

5353
fn as_ref(&self) -> &T {
@@ -61,7 +61,7 @@ impl<T: ?Sized> Wrapper<T> for &T {
6161
}
6262

6363
unsafe fn from_pointer(ptr: NonNull<T>) -> Self {
64-
&*ptr.as_ptr()
64+
unsafe { &*ptr.as_ptr() }
6565
}
6666

6767
fn as_ref(&self) -> &T {
@@ -149,10 +149,10 @@ impl<G: GetLinksWrapped> List<G> {
149149
/// Callers must ensure that `existing` points to a valid entry that is on the list.
150150
pub unsafe fn insert_after(&mut self, existing: NonNull<G::EntryType>, data: G::Wrapped) {
151151
let ptr = data.into_pointer();
152-
let entry = &*existing.as_ptr();
153-
if !self.list.insert_after(entry, ptr.as_ref()) {
152+
let entry = unsafe { &*existing.as_ptr() };
153+
if unsafe { !self.list.insert_after(entry, ptr.as_ref()) } {
154154
// If insertion failed, rebuild object so that it can be freed.
155-
G::Wrapped::from_pointer(ptr);
155+
unsafe { G::Wrapped::from_pointer(ptr) };
156156
}
157157
}
158158

@@ -164,8 +164,8 @@ impl<G: GetLinksWrapped> List<G> {
164164
/// list leads to memory unsafety.
165165
pub unsafe fn remove(&mut self, data: &G::Wrapped) -> Option<G::Wrapped> {
166166
let entry_ref = Wrapper::as_ref(data);
167-
if self.list.remove(entry_ref) {
168-
Some(G::Wrapped::from_pointer(NonNull::from(entry_ref)))
167+
if unsafe { self.list.remove(entry_ref) } {
168+
Some(unsafe { G::Wrapped::from_pointer(NonNull::from(entry_ref)) })
169169
} else {
170170
None
171171
}

‎rust/kernel/miscdev.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,11 @@ impl<T: Sync> FileOpenAdapter for Registration<T> {
8585
type Arg = T;
8686

8787
unsafe fn convert(_inode: *mut bindings::inode, file: *mut bindings::file) -> *const Self::Arg {
88+
// TODO: `SAFETY` comment required here even if `unsafe` is not present,
89+
// because `container_of!` hides it. Ideally we would not allow
90+
// `unsafe` code as parameters to macros.
8891
let reg = crate::container_of!((*file).private_data, Self, mdev);
89-
&(*reg).context
92+
unsafe { &(*reg).context }
9093
}
9194
}
9295

‎rust/kernel/module_param.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,12 @@ pub trait ModuleParam: core::fmt::Display + core::marker::Sized {
7171
let arg = if val.is_null() {
7272
None
7373
} else {
74-
Some(CStr::from_char_ptr(val).as_bytes())
74+
Some(unsafe { CStr::from_char_ptr(val).as_bytes() })
7575
};
7676
match Self::try_from_param_arg(arg) {
7777
Some(new_value) => {
78-
let old_value = (*param).__bindgen_anon_1.arg as *mut Self;
79-
let _ = core::ptr::replace(old_value, new_value);
78+
let old_value = unsafe { (*param).__bindgen_anon_1.arg as *mut Self };
79+
let _ = unsafe { core::ptr::replace(old_value, new_value) };
8080
0
8181
}
8282
None => crate::error::Error::EINVAL.to_kernel_errno(),
@@ -95,9 +95,9 @@ pub trait ModuleParam: core::fmt::Display + core::marker::Sized {
9595
buf: *mut crate::c_types::c_char,
9696
param: *const crate::bindings::kernel_param,
9797
) -> crate::c_types::c_int {
98-
let slice = core::slice::from_raw_parts_mut(buf as *mut u8, crate::PAGE_SIZE);
98+
let slice = unsafe { core::slice::from_raw_parts_mut(buf as *mut u8, crate::PAGE_SIZE) };
9999
let mut buf = crate::buffer::Buffer::new(slice);
100-
match write!(buf, "{}\0", *((*param).__bindgen_anon_1.arg as *mut Self)) {
100+
match unsafe { write!(buf, "{}\0", *((*param).__bindgen_anon_1.arg as *mut Self)) } {
101101
Err(_) => crate::error::Error::EINVAL.to_kernel_errno(),
102102
Ok(()) => buf.bytes_written() as crate::c_types::c_int,
103103
}
@@ -111,7 +111,7 @@ pub trait ModuleParam: core::fmt::Display + core::marker::Sized {
111111
///
112112
/// The `arg` field of `param` must be an instance of `Self`.
113113
unsafe extern "C" fn free(arg: *mut crate::c_types::c_void) {
114-
core::ptr::drop_in_place(arg as *mut Self);
114+
unsafe { core::ptr::drop_in_place(arg as *mut Self) };
115115
}
116116
}
117117

‎rust/kernel/of.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,6 @@ impl PointerWrapper for OfMatchTable {
6969
}
7070

7171
unsafe fn from_pointer(p: *const c_types::c_void) -> Self {
72-
Self(InnerTable::from_pointer(p))
72+
Self(unsafe { InnerTable::from_pointer(p) })
7373
}
7474
}

‎rust/kernel/pages.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ impl<const ORDER: u32> Pages<ORDER> {
107107
}
108108

109109
let mapping = self.kmap(0).ok_or(Error::EINVAL)?;
110-
ptr::copy((mapping.ptr as *mut u8).add(offset), dest, len);
110+
unsafe { ptr::copy((mapping.ptr as *mut u8).add(offset), dest, len) };
111111
Ok(())
112112
}
113113

@@ -127,7 +127,7 @@ impl<const ORDER: u32> Pages<ORDER> {
127127
}
128128

129129
let mapping = self.kmap(0).ok_or(Error::EINVAL)?;
130-
ptr::copy(src, (mapping.ptr as *mut u8).add(offset), len);
130+
unsafe { ptr::copy(src, (mapping.ptr as *mut u8).add(offset), len) };
131131
Ok(())
132132
}
133133

There was a problem loading the remainder of the diff.

0 commit comments

Comments
 (0)
Failed to load comments.