diff options
| -rw-r--r-- | Makefile | 11 | ||||
| -rw-r--r-- | src/cart.c | 44 | ||||
| -rw-r--r-- | src/cart.h | 20 | ||||
| -rw-r--r-- | src/env.c | 109 | ||||
| -rw-r--r-- | src/fb.c | 3 | ||||
| -rw-r--r-- | src/fs.c | 126 | ||||
| -rw-r--r-- | src/fs.h | 2 | ||||
| -rw-r--r-- | src/game.c | 24 | ||||
| -rw-r--r-- | src/input.c | 16 | ||||
| -rw-r--r-- | src/input.h | 2 | ||||
| -rw-r--r-- | src/picow.c | 4 | ||||
| -rw-r--r-- | src/tar.c | 117 | ||||
| -rw-r--r-- | src/tar.h | 17 | ||||
| -rw-r--r-- | src/wasmrt.c | 4 | ||||
| -rw-r--r-- | src/wasmrt.h | 10 | ||||
| -rw-r--r-- | tools/generate-sysroot.c | 35 |
16 files changed, 334 insertions, 210 deletions
@@ -6,11 +6,12 @@ HOSTCC ?= cc PICO8 ?= pico8 WASM2C ?= wasm2c -ARCH ?= $(shell uname -m) -CFLAGS ?= -std=c99 -Wall -Wextra -O2 -MMD -Isrc -Ilib -I$(SYSTEM) \ +ARCH ?= $(shell uname -m) +CFLAGS ?= -std=c99 -Wall -Wextra -O2 -MMD -Isrc -Ilib -I$(SYSTEM) \ $(shell pkg-config sdl3 --cflags) -LDFLAGS ?= $(shell pkg-config sdl3 --libs) -lm -W2CFLAGS ?= --disable-tail-call +HOSTCFLAGS ?= -std=c99 -Wall -Wextra -O2 -MMD +LDFLAGS ?= $(shell pkg-config sdl3 --libs) -lm +W2CFLAGS ?= --disable-tail-call TARGET := build/$(ARCH) OUT := $(TARGET)/out @@ -70,7 +71,7 @@ $(SYSTEM)/%.png: carts/%.p8 $(TOOLS)/%: tools/%.c @ echo "CC\t$@" @ mkdir -p $(dir $@) - @ $(HOSTCC) $(CFLAGS) $< -o $@ + @ $(HOSTCC) $(HOSTCFLAGS) $< -o $@ .PHONY: build/compile_commands.json build/compile_commands.json: $(TOOLS)/ccj @@ -7,8 +7,8 @@ static bool cart_file_path(struct pw_cart_file *file, char const *dir, char const *filename, char const *ext) { - if (!pw_pathjoin(file->path, PW_PATH_MAX, dir, filename, NULL) || - !pw_stripext(file->name, PW_NAME_MAX, filename, ext)) { + if (!pw_pathjoin(file->path, PW_CART_PATH_MAX, dir, filename, NULL) || + !pw_stripext(file->name, PW_CART_NAME_MAX, filename, ext)) { SDL_SetError("invalid cart file name %s", filename); return false; } @@ -78,14 +78,14 @@ struct pw_carts *pw_carts_list(char const *dir) { SDL_qsort(carts->entries, carts->count, sizeof(*carts->entries), cmp_cart_entry); - char multidir[PW_PATH_MAX]; + char multidir[PW_CART_PATH_MAX]; for (size_t i = 0; i < count; i++) { struct pw_cart_entry *entry = &carts->entries[i]; // We are _guaranteed_ that `len < PW_PATH_MAX` by construction, and that // it has a `.p8.png` suffix. This allows us to easily add the `.p8.dir` // suffix for the multi-cart directory. Skip carts without a multi-dir. - size_t len = SDL_strlcpy(multidir, entry->file.path, PW_PATH_MAX); + size_t len = SDL_strlcpy(multidir, entry->file.path, PW_CART_PATH_MAX); SDL_memcpy(multidir + len - 3, "dir", 4); if (!SDL_GetPathInfo(multidir, &pinfo) || pinfo.type != SDL_PATHTYPE_DIRECTORY) { @@ -151,8 +151,8 @@ static bool blit_image(union pw_png_pixel const *image, SDL_Texture *texture) { return false; } - if (surface->w != PW_PNG_WIDTH || surface->h != PW_PNG_HEIGHT || - surface->pitch != PW_PNG_WIDTH * 4 || + if (surface->w != PW_CART_PNG_WIDTH || surface->h != PW_CART_PNG_HEIGHT || + surface->pitch != PW_CART_PNG_WIDTH * 4 || surface->format != SDL_PIXELFORMAT_RGBA32 || (uintptr_t)surface->pixels % sizeof(uint32_t)) { SDL_UnlockTexture(texture); @@ -163,7 +163,7 @@ static bool blit_image(union pw_png_pixel const *image, SDL_Texture *texture) { // Copy over the raw image data to the surface, while clearing the // steganographic encoding of the cart data. uint32_t *pixels = surface->pixels; - for (size_t i = 0; i < PW_PNG_WIDTH * PW_PNG_HEIGHT; i++) { + for (size_t i = 0; i < PW_CART_PNG_WIDTH * PW_CART_PNG_HEIGHT; i++) { union pw_png_pixel px = image[i]; px.raw &= 0xfcfcfcfc; px.ch.a |= 0x03; @@ -181,8 +181,8 @@ struct pw_cart_png *pw_cart_png_init(SDL_Renderer *renderer) { } cart->texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, - SDL_TEXTUREACCESS_STREAMING, PW_PNG_WIDTH, - PW_PNG_HEIGHT); + SDL_TEXTUREACCESS_STREAMING, + PW_CART_PNG_WIDTH, PW_CART_PNG_HEIGHT); if (!cart->texture) { goto error; } @@ -190,9 +190,9 @@ struct pw_cart_png *pw_cart_png_init(SDL_Renderer *renderer) { goto error; } - union pw_png_pixel *image = - pw_png_load(pw_sysroot_unknown_p8_png.data, - pw_sysroot_unknown_p8_png.size, PW_PNG_WIDTH, PW_PNG_HEIGHT); + union pw_png_pixel *image = pw_png_load( + pw_sysroot_unknown_p8_png.data, pw_sysroot_unknown_p8_png.size, + PW_CART_PNG_WIDTH, PW_CART_PNG_HEIGHT); if (!image) { goto error; } @@ -224,7 +224,7 @@ void pw_cart_png_free(struct pw_cart_png *cart) { } static bool load_cart_png(char const *path, SDL_Texture *texture, - uint8_t rom[PW_ROM_SIZE]) { + uint8_t rom[PW_CART_ROM_SIZE]) { SDL_IOStream *png = SDL_IOFromFile(path, "rb"); if (!png) { @@ -255,7 +255,7 @@ static bool load_cart_png(char const *path, SDL_Texture *texture, goto cleanup; } - image = pw_png_load(data, size, PW_PNG_WIDTH, PW_PNG_HEIGHT); + image = pw_png_load(data, size, PW_CART_PNG_WIDTH, PW_CART_PNG_HEIGHT); if (!image) { goto cleanup; } @@ -265,7 +265,7 @@ static bool load_cart_png(char const *path, SDL_Texture *texture, } // Read steganographically encoded cart ROM. - for (size_t i = 0; i < PW_ROM_SIZE; i++) { + for (size_t i = 0; i < PW_CART_ROM_SIZE; i++) { union pw_png_pixel px = image[i]; px.raw &= 0x03030303; rom[i] = (px.ch.a << 6) | (px.ch.r << 4) | (px.ch.g << 2) | px.ch.b; @@ -297,7 +297,7 @@ bool pw_cart_png_load(struct pw_cart_entry *entry, struct pw_cart_png *cart) { return load_cart_png(entry->file.path, cart->texture, cart->rom); } -static bool load_cart_rom(char const *path, uint8_t rom[PW_ROM_SIZE]) { +static bool load_cart_rom(char const *path, uint8_t rom[PW_CART_ROM_SIZE]) { SDL_IOStream *stream = SDL_IOFromFile(path, "rb"); if (!stream) { return false; @@ -306,15 +306,15 @@ static bool load_cart_rom(char const *path, uint8_t rom[PW_ROM_SIZE]) { bool result = false; Sint64 ssize = SDL_GetIOSize(stream); - if (ssize != PW_ROM_SIZE) { + if (ssize != PW_CART_ROM_SIZE) { if (ssize >= 0) { SDL_SetError("cart ROM is incorrect size"); } goto cleanup; } - size_t n = SDL_ReadIO(stream, rom, PW_ROM_SIZE); - if (n != PW_ROM_SIZE) { + size_t n = SDL_ReadIO(stream, rom, PW_CART_ROM_SIZE); + if (n != PW_CART_ROM_SIZE) { goto cleanup; } @@ -339,9 +339,9 @@ struct pw_cart_data *pw_cart_data_load(struct pw_cart_entry *entry, return NULL; } - SDL_strlcpy(cartdat->carts->name, entry->file.name, PW_NAME_MAX); + SDL_strlcpy(cartdat->carts->name, entry->file.name, PW_CART_NAME_MAX); if (cart) { - SDL_memcpy(cartdat->carts->rom, cart->rom, PW_ROM_SIZE); + SDL_memcpy(cartdat->carts->rom, cart->rom, PW_CART_ROM_SIZE); } else if (!load_cart_png(entry->file.path, NULL, cartdat->carts->rom)) { goto error; } @@ -350,7 +350,7 @@ struct pw_cart_data *pw_cart_data_load(struct pw_cart_entry *entry, struct pw_cart *c = &cartdat->carts[i]; struct pw_cart_file *f = &entry->multi[i - 1]; - SDL_strlcpy(c->name, f->name, PW_NAME_MAX); + SDL_strlcpy(c->name, f->name, PW_CART_NAME_MAX); if (!load_cart_rom(f->path, c->rom)) { goto error; } @@ -4,19 +4,19 @@ #include <SDL3/SDL_render.h> /** The maximum supported PICO-8 cart path size. */ -#define PW_PATH_MAX 960 +#define PW_CART_PATH_MAX 960 /** The maximum supported PICO-8 cart name size. */ -#define PW_NAME_MAX 64 +#define PW_CART_NAME_MAX 64 /** The size of a PICO-8 ROM. */ -#define PW_ROM_SIZE 32768 +#define PW_CART_ROM_SIZE 32768 /** The width in pixels of a PICO-8 PNG. */ -#define PW_PNG_WIDTH 160 +#define PW_CART_PNG_WIDTH 160 /** The height in pixels of a PICO-8 PNG. */ -#define PW_PNG_HEIGHT 205 +#define PW_CART_PNG_HEIGHT 205 /** * A PICO-8 cart file that can be loaded. @@ -25,8 +25,8 @@ * enables multi-cart support. */ struct pw_cart_file { - char name[PW_NAME_MAX]; - char path[PW_PATH_MAX]; + char name[PW_CART_NAME_MAX]; + char path[PW_CART_PATH_MAX]; }; /** @@ -55,15 +55,15 @@ struct pw_carts { */ struct pw_cart_png { SDL_Texture *texture; - uint8_t rom[PW_ROM_SIZE]; + uint8_t rom[PW_CART_ROM_SIZE]; }; /** * A PICO-8 cart data. */ struct pw_cart { - char name[PW_NAME_MAX]; - uint8_t rom[PW_ROM_SIZE]; + char name[PW_CART_NAME_MAX]; + uint8_t rom[PW_CART_ROM_SIZE]; }; /** @@ -32,13 +32,13 @@ #define ENV_TM_CURRENT 3198880 #define ENV_TM_TIMEZONE 3198928 -#define ENV_SECONDS_PER_DAY (1000 * 60 * 60 * 24) +#define ENV_SECONDS_PER_DAY (60 * 60 * 24) #define ENV_NS_PER_YEAR 31556952000000000 struct w2c_env *pw_env_init(size_t memory) { size_t bytes = memory << 20; size_t pages = bytes / wasm2c_pico8_pagesize_env_memory; - if (bytes < memory || pages < ENV_MIN_PAGES || + if (memory > SIZE_MAX >> 20 || pages < ENV_MIN_PAGES || pages > wasm2c_pico8_max_env_memory) { SDL_InvalidParamError("memory"); return NULL; @@ -55,7 +55,7 @@ struct w2c_env *pw_env_init(size_t memory) { } env->memory.size = pages * wasm2c_pico8_pagesize_env_memory; env->memory.data_end = env->memory.data + env->memory.size; - SDL_Log("allocated %llu", env->memory.size); + SDL_Log("allocated %" SDL_PRIu64, env->memory.size); env->table.data = SDL_calloc(wasm2c_pico8_min_env_table, sizeof(*env->table.data)); @@ -150,9 +150,10 @@ static uint32_t env_ticks(void) { return (uint32_t)(SDL_GetTicks() & UINT32_MAX); } -static uint32_t env_timetm(struct w2c_env *env, uint32_t time, +static uint32_t env_timetm(struct w2c_env *env, uint32_t timex, bool local_time) { - int64_t ns = SDL_SECONDS_TO_NS(time); + int32_t t = (int32_t)wasm_rt_memory_load32(&env->memory, timex); + int64_t ns = SDL_SECONDS_TO_NS(t); SDL_DateTime dt; if (!SDL_TimeToDateTime(ns, &dt, local_time)) { return 0; @@ -172,19 +173,20 @@ static uint32_t env_timetm(struct w2c_env *env, uint32_t time, if (!SDL_DateTimeToTime(&jan, &ns)) { return 0; } - int day_of_year = (time - SDL_NS_TO_SECONDS(ns)) / ENV_SECONDS_PER_DAY; + int day_of_year = (t - SDL_NS_TO_SECONDS(ns)) / ENV_SECONDS_PER_DAY; - bool is_dst; + bool has_dst, is_dst; if (local_time) { SDL_DateTime jul; if (!SDL_TimeToDateTime(ns, &jan, true) || !SDL_TimeToDateTime(ns + ENV_NS_PER_YEAR / 2, &jul, true)) { return 0; } - is_dst = jan.utc_offset != jul.utc_offset && - dt.utc_offset == SDL_min(jan.utc_offset, jul.utc_offset); + has_dst = jan.utc_offset != jul.utc_offset; + is_dst = + has_dst && dt.utc_offset == SDL_max(jan.utc_offset, jul.utc_offset); } else { - is_dst = false; + has_dst = is_dst = false; } uint32_t tm = ENV_TM_CURRENT; @@ -192,7 +194,7 @@ static uint32_t env_timetm(struct w2c_env *env, uint32_t time, MEM_WRITE(32, env, tm, dt.minute); MEM_WRITE(32, env, tm, dt.hour); MEM_WRITE(32, env, tm, dt.day); - MEM_WRITE(32, env, tm, dt.month); + MEM_WRITE(32, env, tm, dt.month - 1); MEM_WRITE(32, env, tm, dt.year - 1900); MEM_WRITE(32, env, tm, dt.day_of_week); MEM_WRITE(32, env, tm, day_of_year); @@ -200,22 +202,27 @@ static uint32_t env_timetm(struct w2c_env *env, uint32_t time, MEM_WRITE(32, env, tm, dt.utc_offset); if (local_time) { uint32_t tz = w2c_pico8_0x5F_get_timezone(env->context.instance); - wasm_rt_memory_store32(&env->memory, tz, dt.utc_offset); - uint32_t ds = w2c_pico8_0x5F_get_timezone(env->context.instance); - wasm_rt_memory_store32(&env->memory, ds, dt.utc_offset); - - // SDL does not provide an API for getting a timezone name, and we do not - // want to rely on POSIX for this. Just use a fake `LT` and `LST` for - // "local time" and "local daylight savings time" respectively. - uint32_t tn = w2c_pico8_0x5F_get_tzname(env->context.instance); - if (is_dst) { - char const name[] = "LST"; - wasm_rt_memory_store(&env->memory, tn, name, sizeof(name)); - } else { + wasm_rt_memory_store32(&env->memory, tz, -dt.utc_offset); + uint32_t ds = w2c_pico8_0x5F_get_daylight(env->context.instance); + wasm_rt_memory_store32(&env->memory, ds, has_dst); + + // SDL does not provide an API for getting a timezone name, and we do + // not want to rely on POSIX for this. Just use a fake `LT` and `LST` + // for "local time" and "local daylight savings time" respectively. + uint32_t tzn = w2c_pico8_0x5F_get_tzname(env->context.instance); + if (!wasm_rt_memory_load32(&env->memory, tzn)) { char const name[] = "LT"; - wasm_rt_memory_store(&env->memory, tn, name, sizeof(name)); - }; + wasm_rt_memory_store32(&env->memory, tzn, + env_strndup(env, name, sizeof(name))); + } + if (!wasm_rt_memory_load32(&env->memory, tzn + 4)) { + char const name[] = "LST"; + wasm_rt_memory_store32(&env->memory, tzn + 4, + env_strndup(env, name, sizeof(name))); + } + uint32_t tn = + wasm_rt_memory_load32(&env->memory, tzn + 4 * (uint32_t)is_dst); MEM_WRITE(32, env, tm, tn); } else { MEM_WRITE(32, env, tm, ENV_TM_TIMEZONE); @@ -234,7 +241,7 @@ static SDL_NORETURN void env_unimplemented(char const *name) { } static SDL_NORETURN void env_badasm(char const *i, uint32_t code) { - SDL_LogCritical(0, "unknown ASM (%s) code %d", i, code); + SDL_LogCritical(0, "unknown ASM (%s) code %" SDL_PRIu32, i, code); env_abort(); } @@ -303,8 +310,10 @@ void w2c_env_0x5FSDL_GetWindowSize(struct w2c_env *env, uint32_t window, uint32_t w2c_env_0x5FSDL_Init(struct w2c_env *env, uint32_t flags) { (void)flags; - env->data.errstr = - w2c_pico8_0x5Fmalloc(env->context.instance, ENV_ERROR_MAX_SIZE); + if (!env->data.errstr) { + env->data.errstr = + w2c_pico8_0x5Fmalloc(env->context.instance, ENV_ERROR_MAX_SIZE); + } return 0; } @@ -487,8 +496,8 @@ void w2c_env_0x5F_0x5Flock(struct w2c_env *env, uint32_t ptr) { } void w2c_env_0x5F_0x5FsetErrNo(struct w2c_env *env, uint32_t value) { - uint32_t errno = w2c_pico8_0x5F_0x5Ferrno_location(env->context.instance); - wasm_rt_memory_store32(&env->memory, errno, value); + uint32_t err = w2c_pico8_0x5F_0x5Ferrno_location(env->context.instance); + wasm_rt_memory_store32(&env->memory, err, value); } uint32_t w2c_env_0x5F_0x5Fsyscall140(struct w2c_env *env, uint32_t which, @@ -670,12 +679,12 @@ uint32_t w2c_env_0x5Femscripten_asm_const_i(struct w2c_env *env, case 1: return (uint32_t)env->context.cartdat->count; case 2: - // Gets setta byte from the embedded ROM data, note that we need to convert + // Gets a byte from the embedded ROM data, note that we need to convert // the byte position to a cart index and offset within that cart. { - uint32_t i = env->data.cartpos / PW_ROM_SIZE; + uint32_t i = env->data.cartpos / PW_CART_ROM_SIZE; if (i < env->context.cartdat->count) { - uint32_t offset = env->data.cartpos++ % PW_ROM_SIZE; + uint32_t offset = env->data.cartpos++ % PW_CART_ROM_SIZE; return env->context.cartdat->carts[i].rom[offset]; } else { return 0; @@ -683,9 +692,9 @@ uint32_t w2c_env_0x5Femscripten_asm_const_i(struct w2c_env *env, } case 4: if (env->data.cartname.index < env->context.cartdat->count && - env->data.cartname.pos < PW_NAME_MAX) { + env->data.cartname.pos < PW_CART_NAME_MAX) { return env->context.cartdat->carts[env->data.cartname.index] - .rom[env->data.cartname.pos++]; + .name[env->data.cartname.pos++]; } else { return 0; } @@ -840,7 +849,7 @@ uint32_t w2c_env_0x5Femscripten_asm_const_iiiiiii(struct w2c_env *env, (void)e; (void)f; switch (code) { - case 17: + case 18: // PICO-8 can show a an image popup. I am not sure what it is used for // (maybe for downloading the .p8.png file?), but ignore it. SDL_LogDebug(0, "ignoring attempt to show image popup"); @@ -878,7 +887,7 @@ void w2c_env_0x5Femscripten_async_wget_data(struct w2c_env *env, uint32_t url, (void)onload; char urlstr[256] = {0}; - wasm_rt_memory_load(&env->memory, url, urlstr, sizeof(url) - 1); + wasm_rt_memory_loada(&env->memory, url, urlstr, sizeof(urlstr)); SDL_LogDebug(0, "ignoring attempt to fetch %s", urlstr); w2c_pico8_dynCall_vi(env->context.instance, onerror, userdata); @@ -922,7 +931,7 @@ void w2c_env_0x5Femscripten_set_main_loop(struct w2c_env *env, uint32_t func, void w2c_env_0x5Fexit(struct w2c_env *env, uint32_t code) { // Simulate an exit by signaling that an exit was requested and then trap, // and handling this in the host. - SDL_LogDebug(0, "exiting with code: %d", code); + SDL_LogDebug(0, "exiting with code: %" SDL_PRIu32, code); env->data.state.shutdown = true; wasm_rt_trap(WASM_RT_TRAP_UNREACHABLE); } @@ -951,6 +960,10 @@ void w2c_env_0x5Flongjmp(struct w2c_env *env, uint32_t jmpbuf, uint32_t value) { uint32_t w2c_env_0x5Fstrftime(struct w2c_env *env, uint32_t buf, uint32_t sz, uint32_t fmt, uint32_t tm) { + if (!sz) { + return 0; + } + // AFAICT, PICO-8 only ever formats `struct tm`s with a single format string, // so instead of relying on `strftime` (which has quite a few portability // papercuts), just implement the bear minimum of what we need. @@ -958,8 +971,9 @@ uint32_t w2c_env_0x5Fstrftime(struct w2c_env *env, uint32_t buf, uint32_t sz, // Check that the format matches the single one we support, and it not, write // the empty string and return a written length of 0. - wasm_rt_memory_load(&env->memory, fmt, buffer, sizeof(buffer) - 1); - if (SDL_strcmp(buffer, "%Y-%m-%d %H:%M:%S")) { + size_t fmtlen = + wasm_rt_memory_loada(&env->memory, fmt, buffer, sizeof(buffer)); + if (fmtlen >= sizeof(buffer) || SDL_strcmp(buffer, "%Y-%m-%d %H:%M:%S")) { wasm_rt_memory_store8(&env->memory, buf, 0); return 0; } @@ -970,22 +984,21 @@ uint32_t w2c_env_0x5Fstrftime(struct w2c_env *env, uint32_t buf, uint32_t sz, .minute = wasm_rt_memory_load32_unchecked(&env->memory, tm + 4), .hour = wasm_rt_memory_load32_unchecked(&env->memory, tm + 8), .day = wasm_rt_memory_load32_unchecked(&env->memory, tm + 12), - .month = wasm_rt_memory_load32_unchecked(&env->memory, tm + 16), + .month = wasm_rt_memory_load32_unchecked(&env->memory, tm + 16) + 1, .year = wasm_rt_memory_load32_unchecked(&env->memory, tm + 20) + 1900, }; int n = SDL_snprintf(buffer, sizeof(buffer), "%d-%02d-%02d %02d:%02d:%02d", dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second); - if (n < 0 || (size_t)n >= sizeof(buffer)) { + if (n < 0 || (size_t)n >= sizeof(buffer) || (uint32_t)n >= sz) { wasm_rt_memory_store8(&env->memory, buf, 0); return 0; } - if (sz) { - wasm_rt_memory_store(&env->memory, buf, buffer, sz - 1); - wasm_rt_memory_store8(&env->memory, buf + sz - 1, 0); - } - return n; + uint32_t nz = (uint32_t)n; + wasm_rt_memory_store(&env->memory, buf, buffer, nz + 1); + + return nz; } uint32_t w2c_env_0x5Ftime(struct w2c_env *env, uint32_t time) { @@ -1023,7 +1036,7 @@ void w2c_env_invoke_vii(struct w2c_env *env, uint32_t fn, uint32_t a, uint32_t sp = w2c_pico8_stackSave(env->context.instance); env->data.frame = &frame; - if (setjmp(frame.buf)) { + if (!setjmp(frame.buf)) { w2c_pico8_dynCall_vii(env->context.instance, fn, a, b); } else { // Stack unwinding - restore the stack pointer. @@ -65,7 +65,8 @@ bool pw_fb_iterate(struct pw_framebuffer *fb) { static uint8_t project_component(float r, float start, float size, uint8_t dim) { - if (SDL_fabsf(size) < 1.) { + if (SDL_isnan(r) || SDL_isnan(start) || SDL_isnan(size) || + SDL_fabsf(size) < 1.) { return 0; } @@ -1,4 +1,5 @@ #include <SDL3/SDL_error.h> +#include <SDL3/SDL_filesystem.h> #include <SDL3/SDL_log.h> #include "fs.h" @@ -122,40 +123,49 @@ struct pw_fs *pw_fs_init(char const *path) { if (tar) { bool ok; for (;;) { - size_t blocks; - struct pw_fs_node_buffer w = {.type = PW_FS_NODE_BUFFER}; - char const *p = pw_tar_read(tar, &w.data, &w.size, &blocks); - if (!normalize_path(&p)) { + struct pw_tar_entry f; + if (!pw_tar_read(tar, &f)) { ok = false; break; } - if (!w.data) { + if (!f.data) { ok = true; break; } - w.capacity = blocks * PW_TAR_BLOCK_SIZE; + + 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(w.data); + 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(w.data); + SDL_free(f.data); + SDL_free(e); ok = false; break; } if (!append_entry(&fs->root, e)) { - SDL_free(w.data); + SDL_free(f.data); + SDL_free(e); goto error; } - e->node.w = w; + 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) { @@ -243,12 +253,20 @@ bool pw_fs_sync(struct pw_fs *fs) { return true; } - struct pw_tar *tar = pw_tar_open(fs->path, PW_TAR_OPEN_WRITE); + 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) { - return false; + goto cleanup; } - bool ok = false; for (size_t i = 0; i < fs->root.count; ++i) { struct pw_fs_entry *e = fs->root.entries[i]; @@ -264,15 +282,36 @@ bool pw_fs_sync(struct pw_fs *fs) { } } - // Write the "end-of-archive" block, marking the virtual file-system - // as no longer being dirty on success. - if (pw_tar_write(tar, "", NULL, 0)) { + // 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: - pw_tar_free(tar); + 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; } @@ -386,7 +425,7 @@ bool pw_fs_open(struct pw_fs *fs, char const *path, enum pw_fs_open_flag flags, return SDL_SetError("file does not exist"); } if (e && e->node.type == PW_FS_NODE_STATIC && - ((s->flags & PW_FS_STREAM_WRITE) || (flags & PW_O_TRUNC))) { + (s->flags & PW_FS_STREAM_WRITE)) { fs->err = PW_EACCES; return SDL_SetError("cannot modify read-only file"); } @@ -403,6 +442,7 @@ bool pw_fs_open(struct pw_fs *fs, char const *path, enum pw_fs_open_flag flags, s->node = &e->node; s->pos = 0; if (flags & PW_O_TRUNC) { + fs->dirty = true; e->node.w.size = 0; } @@ -410,7 +450,7 @@ bool pw_fs_open(struct pw_fs *fs, char const *path, enum pw_fs_open_flag flags, return true; } -struct pw_fs_stream *get_stream(struct pw_fs *fs, pw_fd fd) { +static struct pw_fs_stream *get_stream(struct pw_fs *fs, pw_fd fd) { if (!fs) { SDL_InvalidParamError("fs"); return NULL; @@ -459,7 +499,19 @@ bool pw_fs_seek(struct pw_fs *fs, pw_fd fd, int64_t offset, return false; } - struct pw_fs_node_static *r = &s->node->r; + 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) { @@ -470,7 +522,7 @@ bool pw_fs_seek(struct pw_fs *fs, pw_fd fd, int64_t offset, pos = s->pos; break; case PW_SEEK_END: - pos = r->size; + pos = size; break; default: fs->err = PW_EINVAL; @@ -526,11 +578,16 @@ uint8_t const *pw_fs_read(struct pw_fs *fs, pw_fd fd, uint32_t len, return NULL; } - struct pw_fs_node_static *r; + 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: - r = &s->node->r; + data = s->node->w.data; + size = s->node->w.size; break; default: fs->err = PW_EBADF; @@ -539,18 +596,18 @@ uint8_t const *pw_fs_read(struct pw_fs *fs, pw_fd fd, uint32_t len, } // In case we seeked past the end of the file, read nothing. - if (s->pos >= r->size) { + if (s->pos >= size) { *sz = 0; - return r->data + r->size; + return data + size; } size_t end = s->pos + (size_t)len; if (end < s->pos) { end = SIZE_MAX; } - end = SDL_min(end, r->size); + end = SDL_min(end, size); - uint8_t const *buffer = r->data + s->pos; + uint8_t const *buffer = data + s->pos; *sz = end - s->pos; s->pos = end; @@ -643,6 +700,19 @@ bool pw_fs_flush(struct pw_fs *fs, pw_fd fd) { 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') { @@ -650,7 +720,7 @@ bool pw_fs_flush(struct pw_fs *fs, pw_fd fd) { } b->data[i] = '\0'; - SDL_Log("PICO-8> %s", b->data + offset); + SDL_Log("PICO-8>%c %s", marker, b->data + offset); offset = i + 1; } @@ -108,7 +108,7 @@ enum pw_fs_errno { PW_EEXIST = 17, PW_EINVAL = 22, PW_EMFILE = 24, - PW_ENOTTY = 24, + PW_ENOTTY = 25, PW_EFBIG = 27, PW_EOVERFLOW = 75, }; @@ -48,6 +48,9 @@ error: if (game->input) { pw_input_free(game->input); } + if (game->userdat) { + pw_fs_free(game->userdat); + } SDL_free(game); return NULL; @@ -65,6 +68,7 @@ void pw_game_free(struct pw_game *game) { pw_input_free(game->input); pw_fb_free(game->fb); pw_env_free(game->env); + pw_fs_free(game->userdat); SDL_free(game); } @@ -83,13 +87,15 @@ bool pw_game_start(struct pw_game *game, struct pw_cart_data *cartdat) { } game->cartdat = cartdat; - pw_env_link(game->env, (struct pw_env_ctx){ - .fb = game->fb, - .input = game->input, - .cartdat = game->cartdat, - .userdat = game->userdat, - .instance = &game->instance, - }); + if (!pw_env_link(game->env, (struct pw_env_ctx){ + .fb = game->fb, + .input = game->input, + .cartdat = game->cartdat, + .userdat = game->userdat, + .instance = &game->instance, + })) { + return false; + } wasm2c_pico8_instantiate(&game->instance, game->env, NULL); struct wasm_rt_trap_handler_t handler; @@ -150,6 +156,10 @@ bool pw_game_iterate(struct pw_game *game) { } if (wasm_rt_trapped(&handler)) { + // Make sure to reset any leftover invocation frames in case of + // a trap, as they point to invalid stack addresses. + game->env->data.frame = NULL; + // In case we trapped for an `_exit` call, treat it as a shutdown // request instead of a trap. if (game->env->data.state.shutdown) { diff --git a/src/input.c b/src/input.c index 9e48729..e2c5298 100644 --- a/src/input.c +++ b/src/input.c @@ -139,7 +139,7 @@ static bool handle_button(struct pw_input *input, struct pw_players *players, return true; } -static bool enqueue_item(struct pw_keyboard_queue *queue, int32_t item) { +static bool enqueue_item(struct pw_keyboard_queue *queue, uint32_t item) { size_t next = (queue->end + 1) % PW_KEYBOARD_BUFFER_SIZE; if (next == queue->start) { return false; @@ -150,7 +150,7 @@ static bool enqueue_item(struct pw_keyboard_queue *queue, int32_t item) { return true; } -static bool dequeue_item(struct pw_keyboard_queue *queue, int32_t *item) { +static bool dequeue_item(struct pw_keyboard_queue *queue, uint32_t *item) { if (queue->start == queue->end) { return false; } @@ -200,7 +200,8 @@ static int8_t scancode_to_p8scii(SDL_Scancode sc, SDL_Keymod mod) { static bool handle_key(struct pw_input *input, SDL_KeyboardEvent *event) { if (event->scancode < 0 || event->scancode > PW_SCANCODE_MASK) { - return false; + // Ignore unsupported scancodes. + return true; } uint32_t sc = (uint32_t)event->scancode; @@ -212,13 +213,13 @@ static bool handle_key(struct pw_input *input, SDL_KeyboardEvent *event) { } sc |= (uint32_t)event->mod << PW_SCANCODE_MOD_SHIFT; - if (!enqueue_item(&input->keyboard.scancodes, (int32_t)sc)) { + if (!enqueue_item(&input->keyboard.scancodes, sc)) { SDL_LogDebug(0, "keyboard event queue full, dropping scancode"); } if (event->down) { int8_t key = scancode_to_p8scii(event->scancode, event->mod); - if (!enqueue_item(&input->keyboard.text, (int32_t)key)) { + if (!enqueue_item(&input->keyboard.text, (uint32_t)key)) { SDL_LogDebug(0, "keyboard text queue full, dropping key %d", key); } } @@ -456,9 +457,8 @@ bool pw_input_poll(struct pw_input *input, union pw_input_event *event) { input->mouse.xrel || input->mouse.yrel; } - int32_t item; - if (dequeue_item(&input->keyboard.scancodes, &item)) { - uint32_t sc = (uint32_t)item; + uint32_t sc; + if (dequeue_item(&input->keyboard.scancodes, &sc)) { SDL_Scancode scancode = (SDL_Scancode)(sc & PW_SCANCODE_MASK); SDL_Keymod mod = (SDL_Keymod)(sc >> PW_SCANCODE_MOD_SHIFT); diff --git a/src/input.h b/src/input.h index d266977..7810918 100644 --- a/src/input.h +++ b/src/input.h @@ -42,7 +42,7 @@ enum pw_keymod { * A queue used for storing queued key events and text input. */ struct pw_keyboard_queue { - int32_t items[PW_KEYBOARD_BUFFER_SIZE]; + uint32_t items[PW_KEYBOARD_BUFFER_SIZE]; size_t start; size_t end; }; diff --git a/src/picow.c b/src/picow.c index 7db76fb..a0e51e4 100644 --- a/src/picow.c +++ b/src/picow.c @@ -81,7 +81,8 @@ SDL_AppResult SDL_AppInit(void **appstate, int argc, char **argv) { return failf("failed to create window"); } - if (!SDL_SetWindowMinimumSize(state->window, PW_PNG_WIDTH, PW_PNG_HEIGHT)) { + if (!SDL_SetWindowMinimumSize(state->window, PW_CART_PNG_WIDTH, + PW_CART_PNG_HEIGHT)) { return failf("failed to configure minimum window size"); } if (!SDL_SetRenderVSync(state->renderer, 1)) { @@ -127,6 +128,7 @@ SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) { if (!pw_players_event(state->players, event)) { return failf("failed to player controller connection events"); } + /* fallthrough */ default: switch (state->scene) { case PW_SCENE_CART_SELECTION: @@ -59,12 +59,14 @@ struct pw_tar *pw_tar_open(char const *path, enum pw_tar_open_flag flag) { return tar; } -static void close_archive(struct pw_tar *tar) { - if (tar->stream && !SDL_CloseIO(tar->stream)) { +static bool close_archive(struct pw_tar *tar) { + bool ok = !tar->stream || SDL_CloseIO(tar->stream); + if (!ok) { SDL_LogWarn(0, "unexpected error closing tar IO stream: %s", SDL_GetError()); } tar->stream = NULL; + return ok; } void pw_tar_free(struct pw_tar *tar) { @@ -73,7 +75,7 @@ void pw_tar_free(struct pw_tar *tar) { return; } - close_archive(tar); + (void)close_archive(tar); SDL_free(tar); } @@ -135,7 +137,7 @@ static uint64_t parse_octal(struct pw_tar *tar, size_t offset, size_t len) { static bool check_magic(struct pw_tar *tar) { static char const magic[] = "ustar\0" "00"; - return !SDL_memcmp(tar->block + 257, magic, sizeof(magic)); + return !SDL_memcmp(tar->block + 257, magic, 8); } static uint64_t compute_checksum(struct pw_tar *tar) { @@ -151,91 +153,103 @@ static uint64_t compute_checksum(struct pw_tar *tar) { } static bool verify_checksum(struct pw_tar *tar) { - return compute_checksum(tar) == parse_octal(tar, 146, 8); + return compute_checksum(tar) == parse_octal(tar, 148, 8); } -static bool has_filename_prefix(struct pw_tar *tar) { return tar->block[345]; } +static void join_filename(struct pw_tar *tar, struct pw_tar_entry *e) { + char const *b = (char const *)tar->block; + size_t namelen = SDL_strnlen(b, 100); + size_t prefixlen = SDL_strnlen(b + 345, 155); + + if (prefixlen) { + SDL_memcpy(e->path, b + 345, prefixlen); + e->path[prefixlen] = '/'; + SDL_memcpy(e->path + prefixlen + 1, b, namelen); + e->path[prefixlen + namelen + 1] = '\0'; + } else { + SDL_memcpy(e->path, b, namelen); + e->path[namelen] = '\0'; + } +} static size_t block_count(size_t size) { - return (size + PW_TAR_BLOCK_SIZE - 1) / PW_TAR_BLOCK_SIZE; + return (size / PW_TAR_BLOCK_SIZE) + !!(size % PW_TAR_BLOCK_SIZE); } -char const *pw_tar_read(struct pw_tar *tar, uint8_t **data, size_t *size, - size_t *blocks) { +bool pw_tar_read(struct pw_tar *tar, struct pw_tar_entry *entry) { if (!tar) { - SDL_InvalidParamError("tar"); - return NULL; + return SDL_InvalidParamError("tar"); } - if (!tar->stream) { - SDL_SetError("read past end of archive"); - return NULL; + if (!entry) { + return SDL_InvalidParamError("entry"); } - uint64_t sz; - uint64_t blk; - uint8_t *dat = NULL; + if (!tar->stream) { + return SDL_SetError("read past end of archive"); + } + uint8_t *data = NULL; for (;;) { if (!read_exact(tar, tar->block, sizeof(tar->block))) { - goto error; + break; } if (is_eoa(tar)) { close_archive(tar); - sz = blk = 0; - break; + SDL_zerop(entry); + return true; } if (!check_magic(tar)) { SDL_SetError("not a tar archive"); - goto error; - } - if (has_filename_prefix(tar)) { - SDL_SetError("filename prefixes not supported"); - goto error; + break; } if (!verify_checksum(tar)) { SDL_SetError("checksum verification failed"); - goto error; + break; } - sz = parse_octal(tar, 124, 12); - blk = block_count(sz); + uint64_t size = parse_octal(tar, 124, 12); + if (size > PW_TAR_SIZE_MAX) { + SDL_SetError("file size too large %" SDL_PRIu64, size); + break; + } + size_t blocks = (size_t)block_count(size); char ft = (char)tar->block[156]; if (ft && ft != '0') { SDL_LogDebug(0, "skipping unsupported tar file type %c", ft); - if (!skip_blocks(tar, blk)) { - goto error; + if (!skip_blocks(tar, blocks)) { + break; } continue; } - dat = SDL_malloc(SDL_min(blk, 1) * sizeof(tar->block)); - if (!dat) { - goto error; + size_t capacity = SDL_max(blocks, 1) * sizeof(tar->block); + data = SDL_malloc(capacity); + if (!data) { + break; } - if (!read_exact(tar, dat, blk * sizeof(tar->block))) { - goto error; + if (!read_exact(tar, data, blocks * sizeof(tar->block))) { + break; } - break; + join_filename(tar, entry); + entry->data = data; + entry->size = (size_t)size; + entry->capacity = capacity; + entry->blocks = blocks; + return true; } - *data = dat; - *size = sz; - *blocks = SDL_min(blk, 1); - return (char const *)tar->block; - -error: close_archive(tar); - if (dat) { - SDL_free(dat); + if (data) { + SDL_free(data); } - return NULL; + return false; } static bool write_exact(struct pw_tar *tar, uint8_t const *buffer, @@ -254,7 +268,7 @@ static bool encode_octal(struct pw_tar *tar, size_t offset, size_t len, p[--n] = '\0'; while (n) { - p[--n] = (i & 8) + '0'; + p[--n] = (i & 7) + '0'; i /= 8; } @@ -281,7 +295,7 @@ static void encode_checksum(struct pw_tar *tar) { // The checksum _always_ fits in its location, so we don't need to // check it. It can be at most `504 * 255 + 8 * 32 = 128776 = 0373410` // and fits into 8 octal characters. - encode_octal(tar, 146, 8, compute_checksum(tar)); + encode_octal(tar, 148, 8, compute_checksum(tar)); } bool pw_tar_write(struct pw_tar *tar, char const *path, uint8_t const *data, @@ -292,15 +306,18 @@ bool pw_tar_write(struct pw_tar *tar, char const *path, uint8_t const *data, if (!path) { return SDL_InvalidParamError("path"); } + if (size > PW_TAR_SIZE_MAX) { + return SDL_InvalidParamError("size"); + } if (!tar->stream) { return SDL_SetError("write past end of archive"); } if (!data) { - bool ok = write_exact(tar, empty_block, sizeof(empty_block)); - close_archive(tar); - return ok; + bool ok = write_exact(tar, empty_block, sizeof(empty_block)) && + write_exact(tar, empty_block, sizeof(empty_block)); + return close_archive(tar) && ok; } if (!encode_path(tar, path)) { @@ -2,8 +2,11 @@ #define PW_TAR_H #include <SDL3/SDL_iostream.h> +#include <SDL3/SDL_stdinc.h> #define PW_TAR_BLOCK_SIZE 512 +#define PW_TAR_PATH_MAX 257 +#define PW_TAR_SIZE_MAX ((SIZE_MAX / PW_TAR_BLOCK_SIZE) * PW_TAR_BLOCK_SIZE) /** * A UStar archive stream. @@ -22,6 +25,17 @@ enum pw_tar_open_flag { }; /** + * A read Tar entry. + */ +struct pw_tar_entry { + char path[PW_TAR_PATH_MAX]; + uint8_t *data; + size_t size; + size_t capacity; + size_t blocks; +}; + +/** * Opens a new Tar reader. */ struct pw_tar *pw_tar_open(char const *path, enum pw_tar_open_flag flag); @@ -37,8 +51,7 @@ void pw_tar_free(struct pw_tar *tar); * Sets `data` to the file contents with `size`, `data` is allocated with * `blocks * PW_TAR_BLOCK_SIZE` bytes, and must be freed by the caller. */ -char const *pw_tar_read(struct pw_tar *tar, uint8_t **data, size_t *size, - size_t *blocks); +bool pw_tar_read(struct pw_tar *tar, struct pw_tar_entry *entry); /** * Writes an entry to the Tar file. Write NULL data to indicate the end of diff --git a/src/wasmrt.c b/src/wasmrt.c index 8730c14..6ec73fd 100644 --- a/src/wasmrt.c +++ b/src/wasmrt.c @@ -145,7 +145,9 @@ size_t wasm_rt_memory_loada_unchecked(struct wasm_rt_memory_t const *mem, return i; } } - buf[sz - 1] = '\0'; + if (sz) { + buf[sz - 1] = '\0'; + } return sz; } diff --git a/src/wasmrt.h b/src/wasmrt.h index f161392..8149590 100644 --- a/src/wasmrt.h +++ b/src/wasmrt.h @@ -91,11 +91,6 @@ typedef struct wasm_rt_funcref_t { } wasm_rt_funcref_t; /** - * A null-function reference. - */ -extern struct wasm_rt_funcref_t wasm_rt_funcref_null_value; - -/** * A Web Assembly external reference. */ typedef struct wasm_rt_externref_t { @@ -103,11 +98,6 @@ typedef struct wasm_rt_externref_t { } wasm_rt_externref_t; /** - * A null-external reference. - */ -extern struct wasm_rt_externref_t wasm_rt_externref_null_value; - -/** * Linear Web Assembly memory. */ typedef struct wasm_rt_memory_t { diff --git a/tools/generate-sysroot.c b/tools/generate-sysroot.c index 1acf35f..97d5bb5 100644 --- a/tools/generate-sysroot.c +++ b/tools/generate-sysroot.c @@ -68,24 +68,29 @@ static void write_sysroot_data(struct sysroot_output *out, char const *name, size_t size = (size_t)pos; fprintfx(out->h, "extern struct pw_sysroot_data %s;\n", name); - fprintfx(out->c, "struct pw_sysroot_data %s = {\n", name); - fprintfx(out->c, " .size = %zu,\n", size); - fprintfx(out->c, " .data = {\n"); + fprintfx(out->c, "static uint8_t const %s_data[] = {\n", name); size_t total = 0; - size_t n; - uint8_t data[16]; - while ((n = fread(data, 1, sizeof(data), f))) { - total += n; - - fprintfx(out->c, " "); - for (size_t i = 0; i < n; i++) { - fprintfx(out->c, " 0x%02x,", data[i]); + { + size_t n; + uint8_t data[16]; + while ((n = fread(data, 1, sizeof(data), f))) { + total += n; + + fprintfx(out->c, " "); + for (size_t i = 0; i < n; i++) { + fprintfx(out->c, " 0x%02x,", data[i]); + } + fprintfx(out->c, "\n"); } - fprintfx(out->c, "\n"); } - - fprintfx(out->c, " },\n};\n"); + fprintfx(out->c, + "};\n" + "struct pw_sysroot_data %s = {\n" + " .data = %s_data,\n" + " .size = %zu,\n" + "};\n", + name, name, size); check(total == size, "fread(input)"); fclosex(f); @@ -109,8 +114,8 @@ int main(int argc, char *argv[argc + 1]) { "#include <stddef.h>\n" "#include <stdint.h>\n\n" "struct pw_sysroot_data {\n" + " uint8_t const *data;\n" " size_t size;\n" - " uint8_t data[];\n" "};\n\n"); fprintfx(out.c, "// This file is automatically generated, do not edit by hand.\n" |
