#include #include #include #include "fs.h" #include "path.h" #include "sysroot.h" #include "tar.h" #define BUFFER_SIZE 1024 static uint8_t empty_bytes[] = {0}; static bool init_output(union pw_fs_node *node) { node->w.type = PW_FS_NODE_OUTPUT; node->w.data = SDL_malloc(BUFFER_SIZE); if (!node->w.data) { return false; } node->w.size = 0; node->w.capacity = BUFFER_SIZE; return true; } static int cmp_entry(void const *a, void const *b) { struct pw_fs_entry const *const *ea = a; struct pw_fs_entry const *const *eb = b; return SDL_strcmp((*ea)->path, (*eb)->path); } static bool append_entry(struct pw_fs_mount *m, struct pw_fs_entry *e) { while (m->count >= m->capacity) { size_t capacity = SDL_max(m->capacity, 16) * 2; if (capacity < m->capacity) { return SDL_OutOfMemory(); } void *entries = SDL_realloc(m->entries, capacity * sizeof(*m->entries)); if (!entries) { return SDL_OutOfMemory(); } m->entries = entries; m->capacity = capacity; } m->entries[m->count++] = e; return true; } static void sort_entries(struct pw_fs_mount *m) { SDL_qsort(m->entries, m->count, sizeof(*m->entries), cmp_entry); } static void free_entry(struct pw_fs_entry *e) { union pw_fs_node *n = &e->node; switch (n->type) { case PW_FS_NODE_BUFFER: case PW_FS_NODE_OUTPUT: SDL_free(n->w.data); break; default: break; } SDL_free(e); } static void free_entries(struct pw_fs_mount *m) { for (size_t i = 0; i < m->count; ++i) { free_entry(m->entries[i]); } SDL_free(m->entries); } static bool normalize_path(char const **path) { if (!*path) { return false; } while (**path == '/') { ++(*path); } return **path; } struct pw_fs *pw_fs_init(char const *path) { struct pw_tar *tar = NULL; struct pw_fs *fs = SDL_calloc(1, sizeof(*fs)); if (!fs) { return NULL; } if (path) { fs->path = SDL_strdup(path); if (!fs->path) { goto error; } } fs->root.entries = SDL_malloc(32 * sizeof(*fs->root.entries)); if (!fs->root.entries) { goto error; } fs->root.capacity = 32; { struct pw_fs_entry *datapod = SDL_calloc(1, sizeof(*datapod)); if (!datapod) { goto error; } SDL_strlcpy(datapod->path, "data.pod", PW_FS_PATH_MAX); datapod->node.r.type = PW_FS_NODE_STATIC; datapod->node.r.data = pw_sysroot_pico8_data_pod.data; datapod->node.r.size = pw_sysroot_pico8_data_pod.size; if (!append_entry(&fs->root, datapod)) { goto error; } } if (path) { tar = pw_tar_open(path, PW_TAR_OPEN_READ); } if (tar) { bool ok; for (;;) { struct pw_tar_entry f; if (!pw_tar_read(tar, &f)) { ok = false; break; } if (!f.data) { ok = true; break; } const char *p = f.path; if (!normalize_path(&p)) { SDL_free(f.data); ok = false; break; } struct pw_fs_entry *e = SDL_calloc(1, sizeof(*e)); if (!e) { SDL_free(f.data); goto error; } size_t n = SDL_strlcpy(e->path, p, PW_FS_PATH_MAX); if (n >= PW_FS_PATH_MAX) { SDL_SetError("file path too long '%s'", p); SDL_free(f.data); SDL_free(e); ok = false; break; } if (!append_entry(&fs->root, e)) { SDL_free(f.data); SDL_free(e); goto error; } e->node.type = PW_FS_NODE_BUFFER; e->node.w.data = f.data; e->node.w.size = f.size; e->node.w.capacity = f.capacity; } if (ok) { sort_entries(&fs->root); } else { SDL_LogWarn(0, "could not read cart storage: %s", SDL_GetError()); // Free the loaded entries, if any - since we don't know whether or not // they should be there. for (size_t i = 1; i < fs->root.count; ++i) { free_entry(fs->root.entries[i]); } fs->root.count = 1; // In case the Tar is corrupt, do not clobber it with an empty tar // and fallback to in-memory cart storage. SDL_free(fs->path); fs->path = NULL; } pw_tar_free(tar); tar = NULL; fs->dirty = false; } else if (path && SDL_GetPathInfo(path, NULL)) { SDL_LogWarn(0, "cannot access cart storage: %s", SDL_GetError()); // In case the Tar file exists but we cannot access it, fall back to // in-memory cart storage and prevent writing over the file. SDL_free(fs->path); fs->path = NULL; fs->dirty = false; } else if (path) { SDL_LogDebug(0, "initializing cart storage"); fs->dirty = true; } else { SDL_LogDebug(0, "using in-memory cart storage"); } fs->dev.in.r.type = PW_FS_NODE_STATIC; fs->dev.in.r.data = empty_bytes; fs->dev.in.r.size = 0; if (!init_output(&fs->dev.out) || !init_output(&fs->dev.err)) { goto error; } fs->streams[0].node = &fs->dev.in; fs->streams[0].flags = PW_FS_STREAM_READ; fs->streams[1].node = &fs->dev.out; fs->streams[1].flags = PW_FS_STREAM_WRITE | PW_FS_STREAM_APPEND; fs->streams[2].node = &fs->dev.err; fs->streams[2].flags = PW_FS_STREAM_WRITE | PW_FS_STREAM_APPEND; return fs; error: if (tar) { pw_tar_free(tar); } if (fs->root.entries) { free_entries(&fs->root); } if (fs->dev.out.w.data) { SDL_free(fs->dev.out.w.data); } if (fs->dev.err.w.data) { SDL_free(fs->dev.err.w.data); } if (fs->path) { SDL_free(fs->path); } SDL_free(fs); return NULL; } void pw_fs_free(struct pw_fs *fs) { if (!fs) { SDL_InvalidParamError("fs"); return; } if (fs->root.entries) { free_entries(&fs->root); } SDL_free(fs->dev.out.w.data); SDL_free(fs->dev.err.w.data); if (fs->path) { SDL_free(fs->path); } SDL_free(fs); } bool pw_fs_sync(struct pw_fs *fs) { if (!fs) { return SDL_InvalidParamError("fs"); } // Check if we are using disk-backed storage and if the virtual file-system // is dirty and needs to be written. if (!fs->path || !fs->dirty) { fs->dirty = false; return true; } // Currently, we re-write the entire archive every time we sync it // to the file-system. This is a bit wasteful (and can wear storage // devices). That being said, the "dirty" flag paired with the fact // that PICO-8 does not seem to write often to disk and this tar is // typically quite small, makes this acceptable for now. Log that we // are writing to disk to keep an eye on how often it happens. SDL_LogDebug(0, "writing cart storage to disk %s", fs->path); bool ok = false; char *tmp = NULL; struct pw_tar *tar = NULL; int n = SDL_asprintf(&tmp, "%s.sync", fs->path); if (n < 0) { goto cleanup; } tar = pw_tar_open(tmp, PW_TAR_OPEN_WRITE); if (!tar) { goto cleanup; } for (size_t i = 0; i < fs->root.count; ++i) { struct pw_fs_entry *e = fs->root.entries[i]; // Only persist `user_data` files written by PICO-8. if (e->node.type != PW_FS_NODE_BUFFER || SDL_memcmp(e->path, "user_data/", 10)) { continue; } struct pw_fs_node_buffer *w = &e->node.w; if (!pw_tar_write(tar, e->path, w->data, w->size)) { goto cleanup; } } // Write the "end-of-archive" block. if (!pw_tar_write(tar, "", NULL, 0)) { goto cleanup; } // Move our new storage into place. Note that `SDL_RenamePath` is not // guaranteed to be atomic, so there is technically some chance for // dataloss here, but in practice it should not be an issue. if (SDL_RenamePath(tmp, fs->path)) { fs->dirty = false; ok = true; } cleanup: if (tar) { pw_tar_free(tar); } if (!ok) { // Unfortunately, removing a path sets an error if the path does not // exist, which would hide the true error that got us here. Do the // best we can to copy the error and restore it after trying to clean // up our temporary file. char err[1024]; SDL_strlcpy(err, SDL_GetError(), sizeof(err)); SDL_RemovePath(tmp); SDL_SetError("%s", err); } if (tmp) { SDL_free(tmp); } return ok; } static int cmp_path(void const *a, void const *b) { char const *path = a; struct pw_fs_entry const *const *entry = b; return SDL_strcmp(path, (*entry)->path); } static char const cart_dir[] = "user_data/carts/"; static int cmp_cart_path(void const *a, void const *b) { char const *cart = a; struct pw_fs_entry const *const *entry = b; char const *path = (*entry)->path; if (SDL_strstr(path, cart_dir) == path) { return SDL_strcmp(cart, path + sizeof(cart_dir) - 1); } else { return SDL_strcmp(cart_dir, path); } } static struct pw_fs_entry *find_entry(struct pw_fs *fs, char const *path, bool absolute) { struct pw_fs_entry **e = SDL_bsearch(path, fs->root.entries, fs->root.count, sizeof(*fs->root.entries), cmp_path); // Under some conditions, PICO-8 will `LOAD("CART.P8")` by opening a file // instead of using the embedded cart. To support this, for relative cart // paths look in the `user_data/carts/` directory if we didn't find the // file under root. if (!e && !absolute && (pw_hasext(path, ".p8") || pw_hasext(path, ".p8.png"))) { e = SDL_bsearch(path, fs->root.entries, fs->root.count, sizeof(*fs->root.entries), cmp_cart_path); } if (!e) { return NULL; } return *e; } static struct pw_fs_entry *create_entry(struct pw_fs *fs, char const *path) { struct pw_fs_entry *e = SDL_calloc(1, sizeof(*e)); if (!e) { fs->err = PW_ENOMEM; return NULL; } size_t n = SDL_strlcpy(e->path, path, PW_FS_PATH_MAX); if (n >= PW_FS_PATH_MAX) { fs->err = PW_EINVAL; SDL_InvalidParamError("path"); goto error; } e->node.w.type = PW_FS_NODE_BUFFER; e->node.w.data = SDL_malloc(BUFFER_SIZE); if (!e->node.w.data) { fs->err = PW_ENOMEM; goto error; } e->node.w.size = 0; e->node.w.capacity = BUFFER_SIZE; if (!append_entry(&fs->root, e)) { fs->err = PW_ENOMEM; goto error; } sort_entries(&fs->root); // We added a new file, mark the file-system as dirty to ensure a new Tar // entry gets created for our new file. fs->dirty = true; return e; error: if (e->node.w.data) { SDL_free(e->node.w.data); } SDL_free(e); return NULL; } bool pw_fs_open(struct pw_fs *fs, char const *path, enum pw_fs_open_flag flags, pw_fd *fd) { char const *rawpath = path; if (!fs) { return SDL_InvalidParamError("fs"); } if (!normalize_path(&path)) { fs->err = PW_EINVAL; return SDL_InvalidParamError("path"); } if (!fd) { fs->err = PW_EINVAL; return SDL_InvalidParamError("fd"); } if (flags & PW_O_DIRECTORY) { fs->err = PW_ENOTDIR; return SDL_InvalidParamError("flags"); } int32_t f = 0; for (; f < PW_FS_STREAM_MAX && fs->streams[f].node; ++f) { } if (f >= PW_FS_STREAM_MAX) { fs->err = PW_EMFILE; return SDL_SetError("too many open files"); } struct pw_fs_stream *s = &fs->streams[f]; switch (flags & PW_O_ACCMODE) { case PW_O_RDONLY: if (flags & PW_O_TRUNC) { fs->err = PW_EINVAL; return SDL_InvalidParamError("flags"); } s->flags = PW_FS_STREAM_READ; break; case PW_O_WRONLY: s->flags = PW_FS_STREAM_WRITE; break; case PW_O_RDWR: s->flags = PW_FS_STREAM_READ | PW_FS_STREAM_WRITE; break; default: fs->err = PW_EINVAL; return SDL_InvalidParamError("flags"); } if (flags & PW_O_APPEND) { s->flags |= PW_FS_STREAM_APPEND; } bool absolute = path != rawpath; struct pw_fs_entry *e = find_entry(fs, path, absolute); if (e && (flags & PW_O_CREAT) && (flags & PW_O_EXCL)) { fs->err = PW_EEXIST; return SDL_SetError("file already exists"); } if (!e && !(flags & PW_O_CREAT)) { fs->err = PW_ENOENT; return SDL_SetError("file does not exist"); } if (e && e->node.type == PW_FS_NODE_STATIC && (s->flags & PW_FS_STREAM_WRITE)) { fs->err = PW_EACCES; return SDL_SetError("cannot modify read-only file"); } if (e && e->node.type == PW_FS_NODE_OUTPUT && (s->flags & PW_FS_STREAM_READ)) { fs->err = PW_EACCES; return SDL_SetError("cannot read write-only file"); } if (!e && !(e = create_entry(fs, path))) { return false; } s->node = &e->node; s->pos = 0; if (flags & PW_O_TRUNC) { // Make sure that our truncation persists to disk for files. if (e->node.type == PW_FS_NODE_BUFFER) { fs->dirty = true; } e->node.w.size = 0; } *fd = f; return true; } #define PW_S_IFCHR 0020000 #define PW_S_IFREG 0100000 bool pw_fs_stat(struct pw_fs *fs, char const *path, struct pw_fs_stat *stat) { char const *rawpath = path; if (!fs) { return SDL_InvalidParamError("fs"); } if (!normalize_path(&path)) { fs->err = PW_EINVAL; return SDL_InvalidParamError("path"); } if (!stat) { fs->err = PW_EINVAL; return SDL_InvalidParamError("stat"); } bool absolute = path != rawpath; struct pw_fs_entry *e = find_entry(fs, path, absolute); if (!e) { fs->err = PW_ENOENT; return SDL_SetError("file does not exist"); } switch (e->node.type) { case PW_FS_NODE_STATIC: stat->mode = PW_S_IFCHR | 0444; stat->size = 0; break; case PW_FS_NODE_BUFFER: stat->mode = PW_S_IFREG | 0666; stat->size = (uint64_t)SDL_min(e->node.w.size, UINT64_MAX); break; case PW_FS_NODE_OUTPUT: stat->mode = PW_S_IFCHR | 0222; stat->size = 0; break; default: fs->err = PW_ENOENT; return false; } return true; } static struct pw_fs_stream *get_stream(struct pw_fs *fs, pw_fd fd) { if (!fs) { SDL_InvalidParamError("fs"); return NULL; } if (fd < 0 || fd >= PW_FS_STREAM_MAX || !fs->streams[fd].node) { fs->err = PW_EBADF; SDL_InvalidParamError("fd"); return NULL; } return &fs->streams[fd]; } bool pw_fs_close(struct pw_fs *fs, pw_fd fd) { struct pw_fs_stream *s = get_stream(fs, fd); if (!s) { return false; } bool result = true; // We have some special handing for output streams (i.e. stdout and // stderr) where we write a final log message in case there are // pending bytes, even without a newline. if (s->node->type == PW_FS_NODE_OUTPUT && s->node->w.size) { if (s->node->w.data[s->node->w.size - 1] != '\n') { uint8_t *buffer = pw_fs_write(fs, fd, 1); if (!buffer) { result = false; goto close; } *buffer = '\n'; } result = pw_fs_flush(fs, fd); } close: SDL_zerop(s); return result; } bool pw_fs_seek(struct pw_fs *fs, pw_fd fd, int64_t offset, enum pw_fs_seek_whence whence, int64_t *newpos) { struct pw_fs_stream *s = get_stream(fs, fd); if (!s) { return false; } size_t size; switch (s->node->type) { case PW_FS_NODE_STATIC: size = s->node->r.size; break; case PW_FS_NODE_BUFFER: case PW_FS_NODE_OUTPUT: size = s->node->w.size; break; default: fs->err = PW_EBADF; return SDL_SetError("cannot read from write-only file entry"); } size_t pos; switch (whence) { case PW_SEEK_SET: pos = 0; break; case PW_SEEK_CUR: pos = s->pos; break; case PW_SEEK_END: pos = size; break; default: fs->err = PW_EINVAL; return SDL_InvalidParamError("whence"); } if (offset > 0) { uint64_t uoffset = (uint64_t)offset; if (uoffset > SIZE_MAX - pos) { fs->err = PW_EINVAL; return SDL_InvalidParamError("offset"); } pos += (size_t)uoffset; } else if (offset < 0) { uint64_t uoffset = -(uint64_t)offset; if (uoffset > pos) { fs->err = PW_EINVAL; return SDL_InvalidParamError("offset"); } pos -= (size_t)uoffset; } // This is a little weird - but the final position needs to fit in // a signed 64-bit value (even if we use unsigned `size_t` values // internally). In practice, this should not matter. #if SIZE_MAX > INT64_MAX if (pos > INT64_MAX) { fs->err = PW_EOVERFLOW; return SDL_SetError("seek overflows PICO-8 maximum position"); } #endif s->pos = pos; if (newpos) { *newpos = (int64_t)pos; } return true; } bool pw_fs_cntl(struct pw_fs *fs, pw_fd fd, enum pw_fs_cntl_op op, int32_t *arg) { struct pw_fs_stream *s = get_stream(fs, fd); if (!s) { return false; } if (!arg) { fs->err = PW_EINVAL; return false; } switch (op) { case PW_F_GETFL: { enum pw_fs_open_flag f; if (s->flags & PW_FS_STREAM_READ && s->flags & PW_FS_STREAM_WRITE) { f = PW_O_RDWR; } else if (s->flags & PW_FS_STREAM_READ) { f = PW_O_RDONLY; } else if (s->flags & PW_FS_STREAM_WRITE) { f = PW_O_WRONLY; } else { fs->err = PW_EBADF; return SDL_SetError("invalid file stream flags"); } if (s->flags & PW_FS_STREAM_APPEND) { f |= PW_O_APPEND; } *arg = (int32_t)f; return true; } case PW_F_SETFL: if (*arg & PW_O_APPEND) { s->flags |= PW_FS_STREAM_APPEND; } else { s->flags &= ~PW_FS_STREAM_APPEND; } *arg = 0; return true; default: fs->err = PW_EINVAL; return SDL_SetError("invalid file descriptor operation %d", op); } } uint8_t const *pw_fs_read(struct pw_fs *fs, pw_fd fd, uint32_t len, uint32_t *sz) { struct pw_fs_stream *s = get_stream(fs, fd); if (!s) { return NULL; } if (!sz) { SDL_InvalidParamError("sz"); return NULL; } if (!(s->flags & PW_FS_STREAM_READ)) { fs->err = PW_EBADF; SDL_SetError("cannot read from write-only file stream"); return NULL; } uint8_t const *data; size_t size; switch (s->node->type) { case PW_FS_NODE_STATIC: data = s->node->r.data; size = s->node->r.size; break; case PW_FS_NODE_BUFFER: data = s->node->w.data; size = s->node->w.size; break; default: fs->err = PW_EBADF; SDL_SetError("cannot read from write-only file entry"); return NULL; } // In case we seeked past the end of the file, read nothing. if (s->pos >= size) { *sz = 0; return data + size; } size_t end = s->pos + (size_t)len; if (end < s->pos) { end = SIZE_MAX; } end = SDL_min(end, size); uint8_t const *buffer = data + s->pos; *sz = end - s->pos; s->pos = end; return buffer; } uint8_t *pw_fs_write(struct pw_fs *fs, pw_fd fd, uint32_t len) { struct pw_fs_stream *s = get_stream(fs, fd); if (!s) { return NULL; } if (!(s->flags & PW_FS_STREAM_WRITE)) { fs->err = PW_EBADF; SDL_SetError("cannot write to read-only file stream"); return NULL; } struct pw_fs_node_buffer *w; switch (s->node->type) { case PW_FS_NODE_BUFFER: case PW_FS_NODE_OUTPUT: w = &s->node->w; break; default: fs->err = PW_EBADF; SDL_SetError("cannot write to read-only file entry"); return NULL; } // With the append flag, always move to the end of the file. This // matters when there are multiple file descriptors writing to the // same file. if (s->flags & PW_FS_STREAM_APPEND) { s->pos = w->size; } // If we write 0 bytes, just return right away, as we do not want // to resize the buffer in case we have seeked past EOF. if (!len) { return w->data + w->capacity; } size_t end = s->pos + (size_t)len; if (end < s->pos) { fs->err = PW_EFBIG; SDL_SetError("write past maximum file size"); return NULL; } // Check if we need to grow our buffer. if (end > w->capacity) { size_t capacity = SDL_max(w->capacity * 2, end); uint8_t *data = SDL_realloc(w->data, capacity); if (!data) { fs->err = PW_EFBIG; return NULL; } w->data = data; w->capacity = capacity; } // We cannot know for sure that the caller will actually write the // data to the buffer, which means that it is possible for us to sync // uninitialized malloc data which would be undefined behaviour. To // prevent this, always clear the new portions of the buffer. Note that // POSIX requires holes to be filled with 0s (in case the file was // seeked past the end), so we satisfy that as well. if (end > w->size) { SDL_memset(w->data + w->size, 0, end - w->size); } uint8_t *buffer = w->data + s->pos; w->size = SDL_max(w->size, end); s->pos = end; // In case we are writting to a file's buffer, and not just to stdout // or stderr, make the file system as dirty. if (w->type == PW_FS_NODE_BUFFER) { fs->dirty = true; } return buffer; } bool pw_fs_flush(struct pw_fs *fs, pw_fd fd) { struct pw_fs_stream *s = get_stream(fs, fd); if (!s) { return false; } struct pw_fs_node_buffer *b; switch (s->node->type) { case PW_FS_NODE_OUTPUT: b = &s->node->w; break; default: return true; } char marker; switch (fd) { case 1: marker = '.'; break; case 2: marker = '!'; break; default: marker = '?'; break; } size_t offset = 0; for (size_t i = 0; i < b->size; ++i) { if (b->data[i] != '\n') { continue; } b->data[i] = '\0'; SDL_LogDebug(0, "PICO-8>%c %s", marker, b->data + offset); offset = i + 1; } b->size -= offset; if (offset && b->size) { SDL_memmove(b->data, b->data + offset, b->size); } return true; } enum pw_fs_errno pw_fs_errno(struct pw_fs *fs) { if (!fs) { SDL_InvalidParamError("fs"); return PW_EOK; } return fs->err; }