overdrivenpotato / rust-psp

Rust on PSP. Panic and allocation support. Access PSP system libraries.
Other
638 stars 33 forks source link

Add `SimpleVramAllocator::free_all` and attach a lifetime to VRAM chunks #119

Closed ayrtonm closed 2 years ago

ayrtonm commented 2 years ago

This allows the borrow checker to work with VRAM allocations like I mentioned on discord. I don't think it's super-useful with the current sceGu API, but it doesn't seem any more cumbersome to use which is what I was mainly concerned about. The issue with sceGu is that it takes pointers as arguments so the VRAM chunk lifetime provides no benefit in this particular case

// Borrow the allocator for 'a, get a VRAMChunk<'a> then get a pointer to the
// chunk and drop the VRAMChunk<'a>
let chunk_ptr = allocator.alloc(size).as_mut_ptr();

// Mutably borrowing the allocator for 'b is fine since VRAMChunk<'a> was
// already dropped
allocator.free_all();

// Allocates another chunk overlapping the first one. This is allowed because
// chunk_ptr doesn't have a lifetime and VRAMChunk<'a> was dropped.
let new_chunk = allocator.alloc(size);

// Use-after-free
sceGuDrawBuffer(chunk_ptr);

For this to be useful, you'd have to keep the VRAMChunk<'a> until it's passed to sceGuDrawBuffer like in the PR example. Or we could make a sceGu API that accepts VRAMChunks and calculates the pointer internally.

Also the AtomicU32 in the allocator is just for interior mutability (could've been Cell or RefCell). It doesn't inherently make the allocator thread-safe, but the demos use a singleton anyway so it doesn't matter.

ayrtonm commented 2 years ago

Also @MrAwesome @overdrivenpotato do you remember why the dealloc methods were dropped before #60 was merged? I imagine no one's bumping into the 8MB VRAM limit so it's probably not that useful, but I couldn't find an explanation on that PR.

overdrivenpotato commented 2 years ago

The realloc and dealloc methods in that PR were just stubs with an unimplemented!() body.

ayrtonm commented 2 years ago

I should probably remove the comments in examples/cube, but there's no reason this needs to be a draft.