Skip to content

Improvements to game context #7

@maxdeviant

Description

@maxdeviant

This is the current design we have for accessing the game context stored in the Context object:

impl<G> Context<G> {
    /// Returns the game context.
    pub fn game<'a, 'b>(&'a self) -> &'b G {
        // Extend the lifetime of the game context so that we can borrow it at
        // the same time as the rest of the context.
        //
        // This *should* be safe because:
        //   (1) The game context is opaque within Peacock, so nothing in the
        //       engine will be modifying it,
        //   (2) the game context is not modifiable externally unless
        //   (3) the caller obtains a mutable reference with `game_mut`, which
        //       is then checked by the borrow checker.
        unsafe { std::mem::transmute::<&'a G, &'b G>(&self.game) }
    }

    /// Returns a mutable reference to game context.
    pub fn game_mut(&mut self) -> &mut G {
        &mut self.game
    }
}

I shared this on Twitter and a number of people have come out and said that this is unsound.

A lot of the examples shown aren't working within the full constraints that Peacock enforces, so each one will have to be assessed within Peacock's constraints to determine whether it is actually a problem that can arise.

The game_context example shows a very basic example of how this is used. This can serve as a baseline for building up examples that show how the current implementation is either okay or problematic.

Problematic Examples

Use after free

A use after free error is possible if game is dropped before the Context:

struct Game(u32);

struct Ctx {
    game: Game,
}

impl Ctx {
    pub fn game<'a, 'b>(&'a self) -> &'b Game {
        unsafe { std::mem::transmute(&self.game) }
    }
}

fn tmp<'a>() -> &'a Game {
    let ctx = Ctx {
        game: Game(0x12345678),
    };
    ctx.game()
}

fn main() {
    let g = tmp();
    println!("{:x}", g.0);
}

Aliasing between mutable and immutable borrows

struct Game(u32);

struct Ctx {
    game: Game,
}

impl Ctx {
    pub fn game<'a, 'b>(&'a self) -> &'b Game {
        unsafe { std::mem::transmute(&self.game) }
    }

    /// Returns a mutable reference to game context.
    pub fn game_mut<'b, 'a: 'b>(&'a mut self) -> &'b mut Game {
        &mut self.game
    }
}

fn tmp(ctx: &mut Ctx) -> (&mut Game, &Game) {
    let g = ctx.game();
    (ctx.game_mut(), g)
}

fn main() {
    let mut ctx = Ctx {
        game: Game(0x12345678),
    };
    let (mutg, g) = tmp(&mut ctx);
    println!("{:x}", g.0);

    mutg.0 -= 10;
    println!("{:x}", g.0);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions