Re: [RFC PATCH 2/5] doc: rust: safety standard: add examples
From: Benno Lossin
Date: Thu Jul 25 2024 - 03:47:36 EST
On 19.07.24 18:36, Daniel Almeida wrote:
>> On 17 Jul 2024, at 19:12, Benno Lossin <benno.lossin@xxxxxxxxx> wrote:
>> +Sound ``unsafe`` Code
>> +---------------------
>> +
>> +The Importance of the API Boundary
>> +**********************************
>> +
>> +Is the following API sound?::
>> +
>> + fn foo(r: &mut u32) {
>> + let ptr: *mut u32 = r;
>> + let val;
>> + unsafe {
>> + val = *ptr;
>> + *ptr = 0;
>> + }
>> + }
>> +
>> +It better be sound, but one could argue that it is unsound, since one could replace the ptr
>> +initialization by ``ptr = core::ptr::null_mut()``::
>> +
>> + fn foo(r: &mut u32) {
>> + let ptr: *mut u32 = core::ptr::null_mut();
>> + let val;
>> + unsafe {
>> + val = *ptr;
>> + *ptr = 0;
>> + }
>> + }
>> +
>> +But this modification is not allowed, since it goes beyond the API boundary of ``foo``. This way
>> +any ``unsafe`` code that relies on surrounding safe code could be shown to be unsound. Instead one
>> +should only consider safe code using the API, in this case, there is no way to make the code
>> +incorrect, since a reference is always valid to dereference during its lifetime.
>
> I find this paragraph a bit confusing. Maybe this can be clarified a bit further?
I will try to rephrase this, tell me if it helps. When checking if an
API is sound, you are not allowed to change the code behind the API.
That is because `unsafe` code often relies on the surrounding safe code
to work properly. In the example above, safe code ensures that the raw
pointer `ptr` is valid. This is OK (and also very necessary), since we
expect people to be *aware* of the `unsafe` block and thus more
carefully review the changes in surrounding safe code. If you have safe
code that only interfaces with other safe code you don't need to be this
careful.
Note that this heavily depends on where you put the API boundary. In our
case, we generally have this boundary: driver code <-> `kernel` crate.
But if your driver requires very specific helper code that does not fit
into the `kernel` crate, then you might also have an API boundary there.
If it doesn't help, then it would great to get some more detailed
questions which part(s) you need help with.
---
Cheers,
Benno