From 0b285bec684dc707574296dba86c9cf933756896 Mon Sep 17 00:00:00 2001 From: AlexJones0 Date: Thu, 20 Jun 2024 18:20:43 +0100 Subject: [PATCH] Added snake CHERI demo for sonata Signed-off-by: AlexJones0 --- examples/snake/cherry_bitmap.h | 31 ++ examples/snake/snake.cc | 651 +++++++++++++++++++++++++++++++++ examples/snake/xmake.lua | 6 + examples/snake/xor_shift.cc | 24 ++ examples/snake/xor_shift.hh | 10 + examples/xmake.lua | 19 +- 6 files changed, 740 insertions(+), 1 deletion(-) create mode 100644 examples/snake/cherry_bitmap.h create mode 100644 examples/snake/snake.cc create mode 100644 examples/snake/xmake.lua create mode 100644 examples/snake/xor_shift.cc create mode 100644 examples/snake/xor_shift.hh diff --git a/examples/snake/cherry_bitmap.h b/examples/snake/cherry_bitmap.h new file mode 100644 index 0000000..938ec17 --- /dev/null +++ b/examples/snake/cherry_bitmap.h @@ -0,0 +1,31 @@ +// Copyright lowRISC contributors. +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +#include + +static uint8_t __attribute__((aligned(4))) cherryImage10x10[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x34, 0x22, 0x34, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x34, 0x00, 0x00, 0x22, 0x34, + 0x00, 0x00, 0x22, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, + 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x34, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xCB, 0xFA, 0x00, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x22, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, + 0x00, 0xE0, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x34, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x00, 0xC0, 0x00, 0x00, + 0x00, 0x00, 0xCB, 0xFA, 0x00, 0xF8, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x00, 0xF8, + 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xF8, 0x00, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, +}; + +static uint8_t __attribute__((aligned(4))) cherryImage5x5[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x00, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0x00, + 0x00, 0xC0, 0x00, 0x06, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0xC0, 0x00, + 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, +}; diff --git a/examples/snake/snake.cc b/examples/snake/snake.cc new file mode 100644 index 0000000..d5306ea --- /dev/null +++ b/examples/snake/snake.cc @@ -0,0 +1,651 @@ +// Copyright lowRISC Contributors. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include + +#include "../../libraries/lcd.hh" +#include "cherry_bitmap.h" +#include "xor_shift.hh" + +using Debug = ConditionalDebug; +using namespace sonata::lcd; +using namespace CHERI; + +// Control game speed +static constexpr uint32_t MILLISECONDS_PER_FRAME = 400; +// Small wait between games to avoid accidentally starting the next +static constexpr uint32_t START_MENU_WAIT_MILLISECONDS = 400; + +// Snake speeds up as it gets longer if enabled +static constexpr bool SPEED_SCALING_ENABLED = true; +// If enabled, all joystick motions start the game (not just a press) +static constexpr bool START_ON_ANY_INPUT = true; +// If enabled, displays a cherry bitmap for the fruit instead of a +// green square at 10x10 and 5x5 tile sizes. +static constexpr bool USE_CHERRY_IMAGE = true; + +// Change colour of game elements +static constexpr Color BACKGROUND_COLOR = Color::Black, + BORDER_COLOR = Color::White, + FOREGROUND_COLOR = Color::White, + SNAKE_COLOR = Color::Red; +// Change the size of game elements (will automatically fit display) +static constexpr Size TILE_SIZE = {10, 10}, + TILE_SPACING = { 2, 2}, + BORDER_SIZE = { 4, 3}; + +typedef struct Position +{ + int32_t x; + int32_t y; +} Position; + +enum class Direction +{ + UP = 0, + RIGHT = 1, + DOWN = 2, + LEFT = 3 +}; + +enum class Tile : uint64_t +{ + EMPTY, + SNAKE, + FRUIT +}; + +/** + * @brief Converts a given size_t to an equivalent string representing its + * unsigned base 10 representation in the given buffer. + * + * @param buffer The buffer/string to write the converted number to. Will + * terminate at the end of the string. + * @param num The size_t number to convert + */ +void size_t_to_str_base10(char *buffer, size_t num) +{ + // Parse the digits using repeated remainders mod 10 + int8_t end_idx = 0; + if (num == 0) + { + buffer[end_idx++] = '0'; + } + while (num != 0) + { + int remainder = num % 10; + buffer[end_idx++] = '0' + remainder; + num /= 10; + } + buffer[end_idx--] = '\0'; + + // Reverse the generated string + int8_t start_idx = 0; + while (start_idx < end_idx) + { + char swap = buffer[start_idx]; + buffer[start_idx++] = buffer[end_idx]; + buffer[end_idx--] = swap; + } +} + +/** + * A game of snake for Sonata, using Cheri capability violations to detect when + * the snake reaches the game's boundaries. + */ +class SnakeGame +{ + private: + bool isFirstGame = true, lastGameWon = false; + Tile **gameSpace = nullptr; + + std::vector snakePositions; + Size gameSize, gamePadding; + Position fruitPosition, nextPosition; + Direction currentDirection, lastSeenDirection; + + /** + * @brief Calculate game size and padding information from defined constants + * and display info. + * + * @param lcd The LCD that will be drawn to. + */ + void initialise_game_size(SonataLcd *lcd) + { + Rect screen = + Rect::from_point_and_size(Point::ORIGIN, lcd->resolution()); + Size displaySize = {screen.right - screen.left - BORDER_SIZE.width * 2, + screen.bottom - screen.top - BORDER_SIZE.height * 2}; + Size spacedTileSize = {TILE_SIZE.width + TILE_SPACING.width, + TILE_SIZE.height + TILE_SPACING.height}; + gameSize = {displaySize.width / spacedTileSize.width, + displaySize.height / spacedTileSize.height}; + gamePadding = { + displaySize.width % spacedTileSize.width + TILE_SPACING.width, + displaySize.height % spacedTileSize.height + TILE_SPACING.height}; + gamePadding = {Point::ORIGIN.x + BORDER_SIZE.width + gamePadding.width/2, + Point::ORIGIN.y + BORDER_SIZE.height + + gamePadding.height/2}; + Debug::log("Calculated game size based on settings: {}x{}", + static_cast(gameSize.width), + static_cast(gameSize.height)); + }; + + /** + * @brief Displays the "start game" menu, waiting for an input and + * initialising a random seed based on the first user input. + * + * @param gpio The Sonata GPIO driver to use for I/O operations. + * @param lcd The LCD that will be drawn to. + */ + void wait_for_start(volatile SonataGPIO *gpio, SonataLcd *lcd) + { + Size displaySize = lcd->resolution(); + Point centre = {displaySize.width / 2, displaySize.height / 2}; + lcd->clean(BACKGROUND_COLOR); + + // Text sizes are hard-coded for now as `draw_str` always uses 16pt font + if (isFirstGame) + { + lcd->draw_str({centre.x - 60, centre.y}, + START_ON_ANY_INPUT ? "Move the joystick to start" + : "Press the joystick to start", + BACKGROUND_COLOR, + FOREGROUND_COLOR); + } + else + { + lcd->draw_str({centre.x - 25, centre.y - 15}, + lastGameWon ? "You won!" : "Game over!", + BACKGROUND_COLOR, + FOREGROUND_COLOR); + lastGameWon = false; + // Manually convert and concatenate score string due to no + // implementation of existing utils + char scoreStr[50]; + memcpy(scoreStr, "Your score: ", 12); + size_t_to_str_base10(&scoreStr[12], snakePositions.size() - 1); + lcd->draw_str({centre.x - 31, centre.y - 5}, + scoreStr, + BACKGROUND_COLOR, + FOREGROUND_COLOR); + lcd->draw_str({centre.x - 65, centre.y + 5}, + START_ON_ANY_INPUT + ? "Move the joystick to play again..." + : "Press the joystick to play again...", + BACKGROUND_COLOR, + FOREGROUND_COLOR); + // Wait for a short time to avoid instantly starting the next game + // due to accidental user input + thread_millisecond_wait(START_MENU_WAIT_MILLISECONDS); + } + + // Busy-wait for a valid joystick input + SonataJoystick joystickInp, noInput; + joystickInp = noInput = static_cast(0x0); + bool waitingForInput = true; + while (waitingForInput) { + thread_millisecond_wait(50); + joystickInp = gpio->read_joystick(); + if (!START_ON_ANY_INPUT && joystickInp == SonataJoystick::Pressed) { + waitingForInput = false; + } else if (START_ON_ANY_INPUT && joystickInp != noInput) { + waitingForInput = false; + } + }; + Debug::log("Input detected. Game starting..."); + + // Initialise Pseudo RNG based on cycle counter at time of first input + init_xor_shift(rdcycle64()); + }; + + /** + * @brief Compares the relevant bits of the input joystick state and the + * given direction to determine if the joystick is held in that direction or + * not. + * + * @param joystick The joystick GPIO input + * @param direction The joystick direction to test for + * @return true if the joystick is held in that direction, false otherwise. + */ + bool joystick_in_direction(SonataJoystick joystick, + SonataJoystick direction) + { + return (static_cast(joystick) & + static_cast(direction)) > 0; + }; + + /** + * @brief Reads the GPIO output to find the current joystick output, and + * translates it into a relevant direction. Returns the previous direction + * if no current output. + * + * @param gpio The Sonata GPIO driver to use for I/O operations. + */ + Direction read_joystick(volatile SonataGPIO *gpio) + { + SonataJoystick joystickState = gpio->read_joystick(); + // The joystick can be in many possible directions - we check directions + // in order relative to the current direction so that input prioritises + // turning left/right over staying in the same direction. This avoids + // the issue of input priority for diagonal joystick inputs, and feels + // smoother to play. + Direction directions[4] = { + Direction::UP, Direction::RIGHT, Direction::DOWN, Direction::LEFT}; + SonataJoystick joystickStates[4] = { + SonataJoystick::Up, SonataJoystick::Right, + SonataJoystick::Down, SonataJoystick::Left}; + + uint8_t base; + for (base = 0; base < 4; base++) + { + if (currentDirection == directions[base]) + { + break; + } + } + + for (uint8_t offset = 1; offset <= 4; offset++) + { + if (offset == 2) + { + continue; // Disallow moving in the opposite direction + } + uint8_t idx = (base + offset) % 4; + if (joystick_in_direction(joystickState, joystickStates[idx])) + { + return directions[idx]; + } + } + return lastSeenDirection; + }; + + /** + * @brief Busy waits for a given amount of time, constantly polling for any + * joystick input and recording it to avoid inputs being eaten between + * frames. + * + * @param milliseconds The time to wait for in milliseconds. + * @param gpio The Sonata GPIO driver to use for I/O operations. + */ + void wait_with_input(uint32_t milliseconds, volatile SonataGPIO *gpio) + { + const uint32_t cyclesPerMillisecond = CPU_TIMER_HZ / 1000; + const uint32_t cycles = milliseconds * cyclesPerMillisecond; + const uint64_t start = rdcycle64(); + uint64_t end = start + cycles; + uint64_t current = start; + while (end > current) + { + lastSeenDirection = read_joystick(gpio); + current = rdcycle64(); + } + }; + + /** + * @brief Attempts to generate a new fruit at a random possible position in + * the game. + * + * @return true if a fruit was successfuly generated, or false if it could + * not be generated. + */ + bool generate_new_fruit() + { + if (gameSize.width * gameSize.height <= snakePositions.size()) + { + return false; // Cannot generate a fruit - board is full + } + bool validPosition = false; + while (!validPosition) + { + fruitPosition = { + static_cast(xor_rand() % gameSize.width), + static_cast(xor_rand() % gameSize.height)}; + + validPosition = true; + for (const Position &partPosition : snakePositions) + { + if (partPosition.x == fruitPosition.x && + partPosition.y == fruitPosition.y) + { + validPosition = false; + break; + } + } + } + gameSpace[fruitPosition.y][fruitPosition.x] = Tile::FRUIT; + return true; + } + + /** + * @brief Initialises information required for starting the game, including + * the snake and fruit positions. + */ + void initialise_game() + { + // Allocate a non-contiguous 2D array storing the game (tile) space for + // collision checks, allowing Out Of Bounds memory accesses to trigger + // CHERI capability violations for scoring + gameSpace = + static_cast(malloc(sizeof(Tile *) * gameSize.height)); + for (uint32_t y = 0; y < gameSize.height; y++) + { + gameSpace[y] = + static_cast(malloc(sizeof(Tile) * gameSize.width)); + } + + Position startPosition = {static_cast(gameSize.width / 2), + static_cast(gameSize.height / 2)}; + snakePositions.clear(); + snakePositions.push_back(startPosition); + gameSpace[startPosition.y][startPosition.x] = Tile::SNAKE; + currentDirection = lastSeenDirection = Direction::RIGHT; + generate_new_fruit(); + }; + + /** + * @brief Draws the background (including the border) for the main game. + * + * @param lcd The LCD that will be drawn to. + */ + void draw_background(SonataLcd *lcd) + { + Size lcdSize = lcd->resolution(); + lcd->clean(BORDER_COLOR); + lcd->fill_rect({BORDER_SIZE.width, + BORDER_SIZE.height, + lcdSize.width - BORDER_SIZE.width, + lcdSize.height - BORDER_SIZE.height}, + BACKGROUND_COLOR); + } + + /** + * @brief Get the rectangle bounding box for the game tile at the given + * position, to use for drawing to the display. + * + * @param position The integer tile position (x, y) to draw at. + */ + Rect get_tile_rect(Position position) + { + Size spacedTileSize = {TILE_SIZE.width + TILE_SPACING.width, + TILE_SIZE.height + TILE_SPACING.height}; + return Rect::from_point_and_size( + {gamePadding.width + position.x * spacedTileSize.width, + gamePadding.height + position.y * spacedTileSize.height}, + TILE_SIZE); + } + + /** + * @brief Draw a filled rectangle the size of one game tile at the specified + * position and colour. + * + * @param lcd The LCD that will be drawn to. + * @param position The integer tile position (x, y) to draw at. + * @param color The colour to fill the drawn tile. + */ + void draw_tile(SonataLcd *lcd, Position position, Color color) + { + Rect tileRect = get_tile_rect(position); + lcd->fill_rect(tileRect, color); + } + + /** + * @brief Draw a cherry (fruit) at a given tile position. If TILE_SIZE is + * either 10x10 or 5x5 and USE_CHERRY_IMAGE is set then this will attempt to + * display a relevant bitmap; otherwise it will draw a green rectangle. + * + * @param lcd The LCD that will be drawn to. + * @param position The integer tile position (x, y) to draw at. + */ + void draw_cherry(SonataLcd *lcd, Position position) + { + Rect tileRect = get_tile_rect(position); + if (USE_CHERRY_IMAGE && TILE_SIZE.height == 10 && TILE_SIZE.width == 10) + { + lcd->draw_image_rgb565(tileRect, cherryImage10x10); + } + else if (USE_CHERRY_IMAGE && TILE_SIZE.height == 5 && + TILE_SIZE.width == 5) + { + lcd->draw_image_rgb565(tileRect, cherryImage5x5); + } + else + { + lcd->fill_rect(tileRect, Color::Green); + } + }; + + /** + * @brief Checks whether the snake is colliding with anything (i.e. itself) + * in the game's space. Also responsible for causing the Out of Bounds + * accesses when hitting the game's boundary which trigger CHERI violations + * for scoring. + * + * @return true if the snake is colliding with itself, false otherwise. + * + * @note The attribute nextPosition is used to pass along the snake's + * position instead of using a traditional argument to allow us to use the + * CHERI capability mechanisms for scoring. By keeping a simple function and + * ignoring caller/callee-saves responsibilities we can just change the PCC + * address to a function of the same kind that returns True to continue + * execution after an out of bounds access occurs. + */ + bool __attribute__((noinline)) check_if_colliding() + { + return (gameSpace[nextPosition.y][nextPosition.x] == Tile::SNAKE); + }; + + /** + * @brief Updates the game's state by a frame, advancing the snake forward + * by 1 step in the input/previous direction, and handling collision and + * fruit-eating logic. Updates the display by drawing only relevant/new + * information, rather than drawing everything each frame. + * + * @param lcd The LCD that will be drawn to. + * @param position The integer tile position (x, y) to draw at. + * @return true if the game is still active, false if the game is over. + */ + bool update_game_state(volatile SonataGPIO *gpio, SonataLcd *lcd) + { + currentDirection = read_joystick(gpio); + + int8_t dx, dy; + switch (currentDirection) + { + case Direction::UP: + dx = -1; + dy = 0; + break; + case Direction::RIGHT: + dx = 0; + dy = -1; + break; + case Direction::DOWN: + dx = 1; + dy = 0; + break; + case Direction::LEFT: + dx = 0; + dy = 1; + }; + + Position currentPosition = snakePositions.back(); + nextPosition = {currentPosition.x + dx, currentPosition.y + dy}; + if (check_if_colliding()) + { + Debug::log("Snake collided with something - game over."); + return false; + } + snakePositions.push_back(nextPosition); + gameSpace[nextPosition.y][nextPosition.x] = Tile::SNAKE; + draw_tile(lcd, nextPosition, SNAKE_COLOR); + + if (nextPosition.x != fruitPosition.x || + nextPosition.y != fruitPosition.y) + { + // If not eating a fruit, move the snake's tail + Position tailPosition = snakePositions.front(); + gameSpace[tailPosition.y][tailPosition.x] = Tile::EMPTY; + snakePositions.erase(snakePositions.begin()); + draw_tile(lcd, tailPosition, BACKGROUND_COLOR); + } + else + { + if (!generate_new_fruit()) + { + Debug::log("Snake has filled the screen - game won!"); + lastGameWon = true; + return false; + } + draw_cherry(lcd, fruitPosition); + } + return true; + } + + /** + * @brief Runs the main game loop, updating the snake's movement and drawing + * new information to the display, and regulates update/frame timing. + * + * @param gpio The Sonata GPIO driver to use for I/O operations + * @param lcd The LCD that will be drawn to. + */ + void main_game_loop(volatile SonataGPIO *gpio, SonataLcd *lcd) + { + const uint32_t cyclesPerMillisecond = CPU_TIMER_HZ / 1000; + uint64_t currentTime = rdcycle64(); + + // Draw initial information (to be drawn on top of, rather than + // re-drawing each frame) + draw_background(lcd); + draw_tile(lcd, snakePositions.front(), SNAKE_COLOR); + draw_cherry(lcd, fruitPosition); + + bool gameStillActive = true; + while (gameStillActive) + { + uint64_t nextTime = rdcycle64(); + uint64_t elapsedTimeMilliseconds = + (nextTime - currentTime) / cyclesPerMillisecond; + uint64_t frameTime = MILLISECONDS_PER_FRAME; + if (SPEED_SCALING_ENABLED) + { + // Scale the game's speed in an inverse relationship between + // MILLISECONDS_PER_FRAME and MILLISECONDS_PER_FRAME / 2 + frameTime /= 2; + frameTime += (frameTime / snakePositions.size()); + } + if (elapsedTimeMilliseconds < frameTime) + { + uint64_t remainingTime = frameTime - elapsedTimeMilliseconds; + wait_with_input(remainingTime, gpio); + } + currentTime = rdcycle64(); + + gameStillActive = update_game_state(gpio, lcd); + } + }; + + /** + * @brief Cleans up the non-contiguous 2D game space array used for + * collision checking. + */ + void free_game_space() + { + for (size_t y = 0; y < gameSize.height; y++) + { + free(gameSpace[y]); + } + free(gameSpace); + } + + public: + /** + * @brief Plays a game of snake using the stored state as settings. + * + * @param gpio The Sonata GPIO driver to use for I/O operations. + * @param lcd The LCD that will be drawn to. + */ + void run_game(volatile SonataGPIO *gpio, SonataLcd *lcd) + { + wait_for_start(gpio, lcd); + initialise_game(); + main_game_loop(gpio, lcd); + free_game_space(); + isFirstGame = false; + }; + + /** + * @brief Constructor for a SnakeGame. + * + * @param lcd The LCD that the game will be drawn to. + */ + SnakeGame(SonataLcd *lcd) + { + initialise_game_size(lcd); + }; + + ~SnakeGame() + { + if (gameSpace != nullptr) + { + free_game_space(); + } + }; +}; + +/** + * @brief A minimal function used to replace SnakeGame::check_if_colliding for + * use in error recovery, letting us utilise RISC-V's capability violations with + * a single compartment as a scoring mechanism. + * + * @return True, always. + */ +bool __attribute__((noinline)) returnFromHandledError() +{ + return true; +} + +/** + * @brief Handles any CHERI Capability Violation errors. If the error was a + * Bounds or Tag violation it assumes it is because of the incorrect memory + * access in SnakeGame::check_if_colliding and therefore it recovers the program + * and ends the game. Otherwise, this force unwinds and ends the program. + */ +extern "C" ErrorRecoveryBehaviour +compartment_error_handler(ErrorState *frame, size_t mcause, size_t mtval) +{ + auto [exceptionCode, registerNumber] = extract_cheri_mtval(mtval); + if (exceptionCode == CauseCode::BoundsViolation || + exceptionCode == CauseCode::TagViolation) + { + // If an explicit out of bounds access occurs, or bounds are made + // invalid by some negative array access, the snake has hit the boundary + // of the game and so the game should end. + frame->pcc = (void *)(&returnFromHandledError); + return ErrorRecoveryBehaviour::InstallContext; + } + + Debug::log( + "Unexpected CHERI Capability violation encountered. Stopping..."); + return ErrorRecoveryBehaviour::ForceUnwind; +} + +// Thread entry point. +void __cheri_compartment("snake") snake() +{ + auto gpio = MMIO_CAPABILITY(SonataGPIO, gpio); + auto lcd = SonataLcd(); + Debug::log("Detected display resolution: {} {}", + static_cast(lcd.resolution().width), + static_cast(lcd.resolution().height)); + SnakeGame game = SnakeGame(&lcd); + while (true) + { + game.run_game(gpio, &lcd); + } +} diff --git a/examples/snake/xmake.lua b/examples/snake/xmake.lua new file mode 100644 index 0000000..1b14d43 --- /dev/null +++ b/examples/snake/xmake.lua @@ -0,0 +1,6 @@ +compartment("xor_shift") + add_files("xor_shift.cc") + +compartment("snake") + add_deps("lcd", "debug", "xor_shift") + add_files("snake.cc") diff --git a/examples/snake/xor_shift.cc b/examples/snake/xor_shift.cc new file mode 100644 index 0000000..9965fa1 --- /dev/null +++ b/examples/snake/xor_shift.cc @@ -0,0 +1,24 @@ +#include +#include + +static uint32_t state; + +static uint32_t __cheri_compartment("xor_shift") + xor_shift_32(uint32_t inputState) +{ + inputState ^= (inputState << 11); + inputState ^= (inputState >> 16); + inputState ^= (inputState << 6); + return inputState; +} + +void __cheri_compartment("xor_shift") init_xor_shift(uint32_t seed) +{ + state = seed; +} + +uint32_t __cheri_compartment("xor_shift") xor_rand() +{ + state = xor_shift_32(state); + return state; +} diff --git a/examples/snake/xor_shift.hh b/examples/snake/xor_shift.hh new file mode 100644 index 0000000..89db9cf --- /dev/null +++ b/examples/snake/xor_shift.hh @@ -0,0 +1,10 @@ +#ifndef XOR_SHIFT_H +#define XOR_SHIFT_H + +#include +#include + +void __cheri_compartment("xor_shift") init_xor_shift(uint32_t seed); +uint32_t __cheri_compartment("xor_shift") xor_rand(); + +#endif diff --git a/examples/xmake.lua b/examples/xmake.lua index 6c3efff..6fe2384 100644 --- a/examples/xmake.lua +++ b/examples/xmake.lua @@ -20,7 +20,7 @@ function convert_to_uf2(target) os.execv("uf2conv", { binary_file, "-b0x00101000", "-co", firmware .. ".uf2" }) end -includes("all") +includes("all", "snake") -- A simple demo using only devices on the Sonata board firmware("sonata_simple_demo") @@ -124,3 +124,20 @@ firmware("proximity_test") }, {expand = false}) end) after_link(convert_to_uf2) + +-- Snake demo +firmware("snake_demo") + add_deps("freestanding", "snake") + on_load(function(target) + target:values_set("board", "$(board)") + target:values_set("threads", { + { + compartment = "snake", + priority = 2, + entry_point = "snake", + stack_size = 0x1000, + trusted_stack_frames = 2 + } + }, {expand = false}) + end) + after_link(convert_to_uf2)