aarch64-switch-rs / nx

Userland library for Nintendo Switch homebrew (and other potential purposes), written in pure Rust and some assembly bits
https://aarch64-switch-rs.github.io/nx/
MIT License
118 stars 17 forks source link

Unsoundness #18

Open GnomedDev opened 1 year ago

GnomedDev commented 1 year ago

The safe function FileAccessor::read takes a out_buf: *mut T and from the documentation "Reads data in the given buffer". This should be unsafe as undefined behavior could be triggered by passing in a pointer not valid for writes.

This was just the first thing I encountered that is obviously unsound in this library, it's usage of features directly marked as incomplete_features (eg: specialization) seems suspicious as well and should probably be removed if possible in my opinion and many other functions could be highly dangerous.

Could a policy on safety be documented or a section added to README.md saying this library is highly in progress and currently has unsoundness/reliance on incomplete features?

GnomedDev commented 1 year ago

Another bit of unsoundness I've found, mem::Shared<T> takes a T, boxes it, stores a *mut T and hands out &mut T in a safe function (get). This means a user can acquire 2 &mut references to the T which is a violation of the aliasing XOR mutability rule and results in instant UB in safe code.

pantsman0 commented 3 weeks ago

Unfortunately, the Locked mutex construct also appears to be completely ineffective for implementing Rust's memory model, See Locked::get():

 pub fn get(&self) -> &mut T {
        self.get_lock().lock();
        let obj_ref = unsafe {
            &mut *self.object_cell.get()
        };
        self.get_lock().unlock();
        obj_ref
    }

The lock is taken, but the &mut T is emitted after the lock has been returned. Unsoundness is as simple as calling get() twice.

@GnomedDev If you have any other places you have seen unsoundness, please lave them in the comments because I am looking into them.

mem::Shared<T> is top on my list, though replacing it is difficult as the current design requires CoerceUnsized which is annoying to work with and not designed to be implemented in libs.

GnomedDev commented 3 weeks ago

I would honestly recommend avoiding this library and simply writing bindings to whatever C API there is yourself. I haven't touched NX dev since I opened this issue though, so there may be much better options.