flash: map existing file to memory to use as sandbox flash

This commit is contained in:
S.J.R. van Schaik 2017-03-23 14:51:17 +00:00
parent eca2bc7b17
commit 31740bbb20

View file

@ -4,6 +4,7 @@
#include <string.h> #include <string.h>
#include <sys/mman.h> #include <sys/mman.h>
#include <sys/stat.h>
#include <flash.h> #include <flash.h>
#include <macros.h> #include <macros.h>
@ -11,6 +12,7 @@
#define CONFIG_FLASH_SIZE 4 * MIB #define CONFIG_FLASH_SIZE 4 * MIB
struct stdio_flash_priv { struct stdio_flash_priv {
FILE *fp;
char *data; char *data;
size_t size; size_t size;
}; };
@ -76,6 +78,7 @@ static int stdio_flash_erase(struct flash_dev *dev, uint32_t addr,
struct flash_dev *flash_probe(void) struct flash_dev *flash_probe(void)
{ {
struct stat st;
struct flash_dev *dev; struct flash_dev *dev;
struct stdio_flash_priv *priv; struct stdio_flash_priv *priv;
@ -85,18 +88,25 @@ struct flash_dev *flash_probe(void)
if (!(priv = malloc(sizeof *priv))) if (!(priv = malloc(sizeof *priv)))
goto err_free_dev; goto err_free_dev;
if (!(priv->data = mmap(NULL, CONFIG_FLASH_SIZE, PROT_READ | PROT_WRITE, if (!(priv->fp = fopen("flash.img", "r+b")))
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)))
goto err_free_priv; goto err_free_priv;
memset(priv->data, 0xFF, CONFIG_FLASH_SIZE); if (fstat(fileno(priv->fp), &st) < 0)
priv->size = CONFIG_FLASH_SIZE; goto err_close_fp;
priv->size = st.st_size;
if (!(priv->data = mmap(NULL, priv->size, PROT_READ | PROT_WRITE,
MAP_PRIVATE, fileno(priv->fp), 0)))
goto err_close_fp;
dev->priv = priv; dev->priv = priv;
dev->ops = &stdio_flash_ops; dev->ops = &stdio_flash_ops;
return dev; return dev;
err_close_fp:
fclose(priv->fp);
err_free_priv: err_free_priv:
free(priv); free(priv);
err_free_dev: err_free_dev: