Soundness: AudioContext in isolated ThreadLocal RefCell #973
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR moves the AudioContext out of the overall Context.
Motivation
As discussed in #333 the current versions of
get_context()andget_quad_context()and their uses rely on undefined behavior.While I disagree that this is an issue that warrants a security advisory, I do think that we need to move to a sound solution.
The problem as I see it is that with some future version of rustc or LLVM macroquad might just straight up stop working.
Goals
Approach
Macroquad functions will not use
get_context()anymore, but instead do their context dependent stuff inside a closure provided towith_context(..).with_context(..)internally borrows and unwraps a threadlocalRefCell<Option<Context>>and provides a&mut Contextto the closure.If multiple functions in the callstack try to borrow the context
with_context()will panic.To deal with this some public functions are split into a variant that borrows context and one that takes a
&mut Contextas argument.While I was implementing above across all of macroquad I noticed that the audiomodule is only very lightly coupled to the rest of the Context.
So I decided to spin the AudioContext out into its own threadlocal refcell and put it into its own PR.
Changes in this PR
The
AudioContextis now no longer part ofContext. It lives in its own threadlocalRefCell<Option<QuadSndContext>>.It is intialized via
init_sound()just after the regular context is constructed.It can be used via
with_audio_context()The userfacing API did not change.
I am working on a lot more than just the AudioContext over at https://github.com/kampffrosch94/macroquad_cell/tree/with_context.
But I'd like to validate my approach before I drop a multi thousand line PR 😅