#include #include #include #include #include #include #include "env.h" #include "pico8.h" // PICO-8 allocates a fix 128 Mb heap unconditinoally; but for some platforms, // that may be too much. Specify a lower bound, in 64Kb pages, for the memory // that we allocate in our Web Assembly environment. This _technically_ does // not respect the module's minimum memory size. This lower bound corresponds // to 32 Mb, and is large enough to write the data at the fixed memory offsets // (such as the dynamic top value, and the time data). #define ENV_MIN_PAGES 512 #define ENV_DYNAMICTOP_PTR 3199024 #define ENV_DYNAMIC_BASE 8441936 #define ENV_ERROR_MAX_SIZE 256 #define ENV_KEYDOWN 0x300 #define ENV_KEYUP 0x301 #define ENV_MOUSEMOTION 0x400 // PICO-8 engine is compiled with the Emscripten built-in SDL1.3 library, which // has a different pixel format encoding than SDL3 which is used on the host. // The pixel format used by the engine is: #define ENV_PIXELFORMAT_ABGR8888 0x86762004 #define ENV_TM_CURRENT 3198880 #define ENV_TM_TIMEZONE 3198928 #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 (memory > SIZE_MAX >> 20 || pages < ENV_MIN_PAGES || pages > wasm2c_pico8_max_env_memory) { SDL_InvalidParamError("memory"); return NULL; } struct w2c_env *env = SDL_calloc(1, sizeof(*env)); if (!env) { return NULL; } env->memory.data = SDL_calloc(pages, wasm2c_pico8_pagesize_env_memory); if (!env->memory.data) { goto error; } env->memory.size = pages * wasm2c_pico8_pagesize_env_memory; env->memory.data_end = env->memory.data + env->memory.size; env->table.data = SDL_calloc(wasm2c_pico8_min_env_table, sizeof(*env->table.data)); if (!env->table.data) { goto error; } env->table.size = wasm2c_pico8_min_env_table; return env; error: if (env->memory.data) { SDL_free(env->memory.data); } if (env->table.data) { SDL_free(env->table.data); } SDL_free(env); return NULL; } void pw_env_free(struct w2c_env *env) { if (!env) { SDL_InvalidParamError("env"); return; } SDL_free(env->memory.data); SDL_free(env->table.data); SDL_free(env); } bool pw_env_link(struct w2c_env *env, struct pw_env_ctx context) { if (!env) { return SDL_InvalidParamError("env"); } if (env->memory.size < ENV_MIN_PAGES * wasm2c_pico8_pagesize_env_memory) { return SDL_SetError("cannot write to fixed memory offsets"); } if (!context.fb || !context.input || !context.cart || !context.instance) { return SDL_InvalidParamError("context"); } SDL_memset(env->memory.data, 0, env->memory.size); SDL_memset(env->table.data, 0, env->table.size * sizeof(*env->table.data)); env->context = context; SDL_zerop(&env->data); // Prepare the memory at fixed offsets that come from the host: env->data.dynamictop = ENV_DYNAMICTOP_PTR; wasm_rt_memory_store32_unchecked(&env->memory, env->data.dynamictop, ENV_DYNAMIC_BASE); char tz[] = "GMT"; wasm_rt_memory_store_unchecked(&env->memory, ENV_TM_TIMEZONE, tz, sizeof(tz)); return true; } bool pw_env_shutdown(struct w2c_env *env) { if (!env) { return SDL_InvalidParamError("env"); } if (env->data.state.shutdown) { return true; } // HERE BE DRAGONS... Taking a look at the Web Assembly module exported // by PICO-8, it calls `env_emscripten_asm_iiiiiiiii(10, ...)` with the // `request_shutdown` flag read from global memory offset `2220668`. For // whatever reason, the `SHUTDOWN` menu flag is setting this location in // memory to a non-zero value, but without calling the ASM const. In order // to correctly support shutting down, we need to not only read the flag // from the ASM const, but also this memory offset. This is tied to the // PICO-8 version, so whenever it gets updated, just: // // grep -B2 'asm_const_iiiiiiiii' build/system/pico8.c // // And check the address that is being loaded for the last parameter to the // state update ASM const call. uint32_t value; return wasm_rt_memory_load32_checked(&env->memory, 2220668, &value) && value; } /** * Convenience macro for writing to wasm memory and moving the wasm pointer * forward for that amount. */ #define MEM_WRITE(n, e, a, v) \ do { \ wasm_rt_memory_store##n##_unchecked(&e->memory, a, v); \ a += (n / 8); \ } while (0) static uint32_t env_swap32(uint32_t *slot, uint32_t value) { uint32_t result = *slot; *slot = value; return result; } static uint32_t env_strndup(struct w2c_env *env, char const *s, uint32_t sz) { if (!sz) { size_t ssz = SDL_strlen(s) + 1; if (ssz > UINT32_MAX) { wasm_rt_trap(WASM_RT_TRAP_OOB); } sz = (uint32_t)ssz; } uint32_t ptr = w2c_pico8_0x5Fmalloc(env->context.instance, sz); wasm_rt_memory_store(&env->memory, ptr, s, sz); return ptr; } static uint32_t env_ticks(void) { return (uint32_t)(SDL_GetTicks() & UINT32_MAX); } static uint32_t env_timetm(struct w2c_env *env, uint32_t timex, bool local_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; } SDL_DateTime jan = { .year = dt.year, .month = 1, .day = 1, .hour = 0, .minute = 0, .second = 0, .nanosecond = 0, .day_of_week = 0, .utc_offset = dt.utc_offset, }; if (!SDL_DateTimeToTime(&jan, &ns)) { return 0; } int day_of_year = (t - SDL_NS_TO_SECONDS(ns)) / ENV_SECONDS_PER_DAY; 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; } has_dst = jan.utc_offset != jul.utc_offset; is_dst = has_dst && dt.utc_offset == SDL_max(jan.utc_offset, jul.utc_offset); } else { has_dst = is_dst = false; } uint32_t tm = ENV_TM_CURRENT; MEM_WRITE(32, env, tm, dt.second); 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 - 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); MEM_WRITE(32, env, tm, (uint32_t)is_dst); 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_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_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); } return ENV_TM_CURRENT; } static inline SDL_NORETURN void env_abort() { wasm_rt_trap(WASM_RT_TRAP_UNREACHABLE); } static SDL_NORETURN void env_badasm(char const *i, uint32_t code) { SDL_LogCritical(0, "unknown ASM (%s) code %" SDL_PRIu32, i, code); env_abort(); } static uint32_t env_varg(struct w2c_env *env, uint32_t ap, uint32_t index) { return wasm_rt_memory_load32(&env->memory, ap + index * 4); } uint32_t *w2c_env_DYNAMICTOP_PTR(struct w2c_env *env) { return &env->data.dynamictop; } uint32_t *w2c_env_0x5F_table_base(struct w2c_env *env) { return &env->data.tablebase; } struct wasm_rt_memory_t *w2c_env_memory(struct w2c_env *env) { return &env->memory; } struct wasm_rt_funcref_table_t *w2c_env_table(struct w2c_env *env) { return &env->table; } void w2c_env_0x5FSDL_ClearError(struct w2c_env *env) { (void)env; SDL_ClearError(); } uint32_t w2c_env_0x5FSDL_GetError(struct w2c_env *env) { char err[ENV_ERROR_MAX_SIZE] = {0}; SDL_strlcpy(err, SDL_GetError(), ENV_ERROR_MAX_SIZE); wasm_rt_memory_store(&env->memory, env->data.errstr, err, ENV_ERROR_MAX_SIZE); return env->data.errstr; } uint32_t w2c_env_0x5FSDL_GetModState(struct w2c_env *env) { return (uint32_t)pw_input_keymod(env->context.input); } uint32_t w2c_env_0x5FSDL_GetMouseState(struct w2c_env *env, uint32_t x, uint32_t y) { struct pw_coordinates pos; enum pw_mouse_button button = pw_input_mouse(env->context.input, &pos); if (x) { wasm_rt_memory_store32(&env->memory, x, (int32_t)pos.x); } if (y) { wasm_rt_memory_store32(&env->memory, y, (int32_t)pos.y); } return (uint32_t)button; } uint32_t w2c_env_0x5FSDL_GetTicks(struct w2c_env *env) { (void)env; return env_ticks(); } void w2c_env_0x5FSDL_GetWindowSize(struct w2c_env *env, uint32_t window, uint32_t x, uint32_t y) { (void)window; wasm_rt_memory_store32(&env->memory, x, PW_FB_WIDTH); wasm_rt_memory_store32(&env->memory, y, PW_FB_HEIGHT); } uint32_t w2c_env_0x5FSDL_Init(struct w2c_env *env, uint32_t flags) { (void)flags; if (!env->data.errstr) { env->data.errstr = w2c_pico8_0x5Fmalloc(env->context.instance, ENV_ERROR_MAX_SIZE); } return 0; } void w2c_env_0x5FSDL_LockAudio(struct w2c_env *env) { // Our Wasm runtime runs on a single thread, so there is nothing to lock // for its internal audio buffer. (void)env; } uint32_t w2c_env_0x5FSDL_LockSurface(struct w2c_env *env, uint32_t surface) { if (!surface) { SDL_InvalidParamError("surface"); return (uint32_t)(-1); } wasm_rt_memory_store32(&env->memory, surface + 28, 1); return 0; } uint32_t w2c_env_0x5FSDL_PollEvent(struct w2c_env *env, uint32_t event) { if (!event) { return (uint32_t)pw_input_poll(env->context.input, NULL); } union pw_input_event input; bool remaining = pw_input_poll(env->context.input, &input); if (remaining) { wasm_rt_memory_check(&env->memory, event, 36); switch (input.type) { case PW_INPUT_EVENT_KEY: if (input.key.pressed) { MEM_WRITE(32, env, event, ENV_KEYDOWN); } else { MEM_WRITE(32, env, event, ENV_KEYUP); } MEM_WRITE(32, env, event, 1); // windowID MEM_WRITE(8, env, event, (uint8_t)input.key.pressed); MEM_WRITE(8, env, event, (uint8_t)input.key.repeat); MEM_WRITE(8, env, event, 0); // padding2 MEM_WRITE(8, env, event, 0); // padding3 MEM_WRITE(32, env, event, input.key.scancode); MEM_WRITE(32, env, event, input.key.keycode); MEM_WRITE(16, env, event, (uint16_t)input.key.mod); MEM_WRITE(16, env, event, 0); // keysym.{padding} MEM_WRITE(32, env, event, 0); // keysym.unicode (deprecated) break; case PW_INPUT_EVENT_MOUSE: MEM_WRITE(32, env, event, ENV_MOUSEMOTION); MEM_WRITE(32, env, event, env_ticks()); MEM_WRITE(32, env, event, 1); // windowID MEM_WRITE(32, env, event, 1); // which MEM_WRITE(32, env, event, (uint32_t)input.mouse.button); MEM_WRITE(32, env, event, input.mouse.x); MEM_WRITE(32, env, event, input.mouse.y); MEM_WRITE(32, env, event, input.mouse.xrel); MEM_WRITE(32, env, event, input.mouse.yrel); break; }; } return (uint32_t)remaining; } uint32_t w2c_env_0x5FSDL_SetVideoMode(struct w2c_env *env, uint32_t w, uint32_t h, uint32_t bpp, uint32_t flags) { if (w != PW_FB_WIDTH || h != PW_FB_HEIGHT || bpp != 32 || flags != 0) { SDL_SetError("unsupported video mode"); return 0; } uint32_t result = w2c_pico8_0x5Fmalloc(env->context.instance, 60 + 44 + PW_FB_SIZE); if (!result) { SDL_SetError("failed to allocate surface"); return 0; } uint32_t surface = result; uint32_t format = surface + 60; uint32_t pixels = format + 44; wasm_rt_memory_check(&env->memory, pixels, PW_FB_SIZE); { MEM_WRITE(32, env, surface, flags); MEM_WRITE(32, env, surface, format); MEM_WRITE(32, env, surface, w); MEM_WRITE(32, env, surface, h); MEM_WRITE(32, env, surface, (w * bpp) / 8); MEM_WRITE(32, env, surface, pixels); MEM_WRITE(32, env, surface, 0); // userdata MEM_WRITE(32, env, surface, 0); // locked MEM_WRITE(32, env, surface, 0); // lock_data MEM_WRITE(32, env, surface, 0); // clip_rect.x MEM_WRITE(32, env, surface, 0); // clip_rect.y MEM_WRITE(32, env, surface, w); // clip_rect.w MEM_WRITE(32, env, surface, h); // clip_rect.h MEM_WRITE(32, env, surface, 0); // map MEM_WRITE(32, env, surface, 1); // refcount } { MEM_WRITE(32, env, format, ENV_PIXELFORMAT_ABGR8888); MEM_WRITE(32, env, format, 0); // palette MEM_WRITE(8, env, format, (uint8_t)bpp); MEM_WRITE(8, env, format, (uint8_t)bpp / 8); MEM_WRITE(16, env, format, 0); // padding MEM_WRITE(32, env, format, 0x000000ff); // rmask MEM_WRITE(32, env, format, 0x0000ff00); // gmask MEM_WRITE(32, env, format, 0x00ff0000); // bmask MEM_WRITE(32, env, format, 0xff000000); // amask MEM_WRITE(8, env, format, 0); // rloss MEM_WRITE(8, env, format, 0); // gloss MEM_WRITE(8, env, format, 0); // bloss MEM_WRITE(8, env, format, 0); // aloss MEM_WRITE(8, env, format, 0); // rshift MEM_WRITE(8, env, format, 8); // gshift MEM_WRITE(8, env, format, 16); // bshift MEM_WRITE(8, env, format, 24); // ashift MEM_WRITE(32, env, format, 1); // refcount MEM_WRITE(32, env, format, 0); // next } { wasm_rt_memory_set(&env->memory, pixels, PW_FB_SIZE, 0); } return result; } void w2c_env_0x5FSDL_UnlockAudio(struct w2c_env *env) { // Our Wasm runtime runs on a single thread, so there is nothing to unlock // for its internal audio buffer. (void)env; } void w2c_env_0x5FSDL_UnlockSurface(struct w2c_env *env, uint32_t surface) { if (!surface) { SDL_InvalidParamError("surface"); return; } wasm_rt_memory_check(&env->memory, surface, 60); // Always clear the locked flag as unlocking should never fail. wasm_rt_memory_store32_unchecked(&env->memory, surface + 28, 0); // Now copy over the screen from wasm memory to our framebuffer. Note that // we bounds check _before_ locking the framebuffer, this prevents OOB access // to trap whitout properly unlocking it. uint32_t pixels = wasm_rt_memory_load32_unchecked(&env->memory, surface + 20); wasm_rt_memory_check(&env->memory, pixels, PW_FB_SIZE); size_t pitch; uint8_t *buffer = pw_fb_lock(env->context.fb, &pitch); if (!buffer) { SDL_SetError("unable to lock framebuffer"); return; } for (size_t y = 0; y < PW_FB_HEIGHT; ++y) { wasm_rt_memory_load_unchecked(&env->memory, pixels + y * PW_FB_STRIDE, buffer + y * pitch, PW_FB_STRIDE); } pw_fb_unlock(env->context.fb); } void w2c_env_0x5F_0x5FbuildEnvironment(struct w2c_env *env, uint32_t environ) { char const *vars[] = {"USER=picow", "LOGNAME=picow", "PATH=/", "PWD=/", "HOME=/home/picow", "LANG=C.UTF-8", "_=./picow"}; size_t count = SDL_arraysize(vars); uint32_t array = w2c_pico8_0x5Fmalloc(env->context.instance, (count + 1) * sizeof(uint32_t)); for (uint32_t i = 0; i < count; ++i) { uint32_t addr = array + i * sizeof(uint32_t); uint32_t str = env_strndup(env, vars[i], 0); wasm_rt_memory_store32(&env->memory, addr, str); } wasm_rt_memory_store32(&env->memory, array + count * sizeof(uint32_t), 0); wasm_rt_memory_store32(&env->memory, environ, array); } void w2c_env_0x5F_0x5Flock(struct w2c_env *env, uint32_t ptr) { (void)env; (void)ptr; } void w2c_env_0x5F_0x5FsetErrNo(struct w2c_env *env, uint32_t 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, uint32_t ap) { (void)which; int32_t fd = (int32_t)env_varg(env, ap, 0); int64_t offset = (int64_t)((uint64_t)env_varg(env, ap, 1) << 32) | (int64_t)env_varg(env, ap, 2); uint32_t result = env_varg(env, ap, 3); uint32_t whence = env_varg(env, ap, 4); int64_t pos; if (!pw_fs_seek(env->context.cart->storage, fd, offset, whence, &pos)) { SDL_LogDebug(0, "error seeking file: %s", SDL_GetError()); return -pw_fs_errno(env->context.cart->storage); } wasm_rt_memory_store64(&env->memory, result, pos); return 0; } uint32_t w2c_env_0x5F_0x5Fsyscall145(struct w2c_env *env, uint32_t which, uint32_t ap) { (void)which; int32_t fd = (int32_t)env_varg(env, ap, 0); uint32_t iov = env_varg(env, ap, 1); uint32_t iovcnt = env_varg(env, ap, 2); // Validate that the total size to read would not overflow the result, which // is treated as a _signed_ value (as negative values are used to indicate // errors from the syscall). uint64_t maxn = 0; for (uint32_t i = 0; i < iovcnt; i++) { uint32_t len = wasm_rt_memory_load32(&env->memory, iov + 8 * i + 4); maxn += len; } if (maxn > INT32_MAX) { return -PW_EINVAL; } uint32_t n = 0; for (uint32_t i = 0; i < iovcnt; i++) { uint32_t buffer = wasm_rt_memory_load32(&env->memory, iov + 8 * i); uint32_t len = wasm_rt_memory_load32(&env->memory, iov + 8 * i + 4); uint32_t size; uint8_t const *contents = pw_fs_read(env->context.cart->storage, fd, len, &size); if (!contents) { return -pw_fs_errno(env->context.cart->storage); } wasm_rt_memory_store(&env->memory, buffer, contents, size); n += size; } return n; } uint32_t w2c_env_0x5F_0x5Fsyscall146(struct w2c_env *env, uint32_t which, uint32_t ap) { (void)which; int32_t fd = (int32_t)env_varg(env, ap, 0); uint32_t iov = env_varg(env, ap, 1); uint32_t iovcnt = env_varg(env, ap, 2); // Validate that the total size to write will not overflow the result, which // is treated as a _signed_ value (as negative values are used to indicate // errors from the syscall). uint64_t n = 0; for (uint32_t i = 0; i < iovcnt; i++) { uint32_t len = wasm_rt_memory_load32(&env->memory, iov + 8 * i + 4); n += len; } if (n > INT32_MAX) { return -PW_EINVAL; } for (uint32_t i = 0; i < iovcnt; i++) { uint32_t buffer = wasm_rt_memory_load32(&env->memory, iov + 8 * i); uint32_t len = wasm_rt_memory_load32(&env->memory, iov + 8 * i + 4); uint8_t *contents = pw_fs_write(env->context.cart->storage, fd, len); if (!contents) { return -pw_fs_errno(env->context.cart->storage); } wasm_rt_memory_load(&env->memory, buffer, contents, len); } if (!pw_fs_flush(env->context.cart->storage, fd)) { return -pw_fs_errno(env->context.cart->storage); } return (uint32_t)n; } uint32_t w2c_env_0x5F_0x5Fsyscall195(struct w2c_env *env, uint32_t which, uint32_t ap) { (void)which; char path[256]; if (wasm_rt_memory_loada(&env->memory, env_varg(env, ap, 0), path, sizeof(path)) >= sizeof(path)) { return -PW_EINVAL; } uint32_t stat = env_varg(env, ap, 1); struct pw_fs_stat s; if (!pw_fs_stat(env->context.cart->storage, path, &s)) { return -pw_fs_errno(env->context.cart->storage); } // Return mostly stubbed stat data, our file-system doesn't support most // of the fields. If ever this causes issues with PICO-8 things (which I // have not noticed for any cart), we can implement something. MEM_WRITE(32, env, stat, 0); // st_dev MEM_WRITE(64, env, stat, 0); // st_ino MEM_WRITE(32, env, stat, s.mode); MEM_WRITE(32, env, stat, 0); // st_nlink MEM_WRITE(32, env, stat, 0); // st_uid MEM_WRITE(32, env, stat, 0); // st_gid MEM_WRITE(32, env, stat, 0); // st_rdev MEM_WRITE(64, env, stat, 0); // padding MEM_WRITE(64, env, stat, s.size); MEM_WRITE(32, env, stat, 0); // st_blksize MEM_WRITE(32, env, stat, 0); // st_blocks MEM_WRITE(64, env, stat, 0); // st_atime MEM_WRITE(64, env, stat, 0); // st_mtime MEM_WRITE(64, env, stat, 0); // st_ctime MEM_WRITE(32, env, stat, 0); // unused[0] MEM_WRITE(32, env, stat, 0); // unused[1] return 0; } uint32_t w2c_env_0x5F_0x5Fsyscall220(struct w2c_env *env, uint32_t which, uint32_t ap) { (void)env; (void)which; (void)ap; // Our file-system does not support directories, so any file descriptor // we get here is never a directory. return -PW_ENOTDIR; } uint32_t w2c_env_0x5F_0x5Fsyscall221(struct w2c_env *env, uint32_t which, uint32_t ap) { (void)which; int32_t fd = (int32_t)env_varg(env, ap, 0); uint32_t op = env_varg(env, ap, 1); // _Technically_ the vararg is defined for certain commands. However, // fortunately, reading anywhere in Wasm memory is well-defined, with // the caveat that the value can be gibberish. To simplify the function // interface and our code, just read in unconditionally, even if the // `pw_fs_cntl` will ignore its value when it is not passed in. int32_t arg = (int32_t)env_varg(env, ap, 2); if (!pw_fs_cntl(env->context.cart->storage, fd, op, &arg)) { return -pw_fs_errno(env->context.cart->storage); } return arg; } uint32_t w2c_env_0x5F_0x5Fsyscall5(struct w2c_env *env, uint32_t which, uint32_t ap) { (void)which; char path[256]; if (wasm_rt_memory_loada(&env->memory, env_varg(env, ap, 0), path, sizeof(path)) >= sizeof(path)) { return -PW_EINVAL; } uint32_t flags = env_varg(env, ap, 1); int32_t fd; if (!pw_fs_open(env->context.cart->storage, path, flags, &fd)) { return -pw_fs_errno(env->context.cart->storage); } return fd; } uint32_t w2c_env_0x5F_0x5Fsyscall54(struct w2c_env *env, uint32_t which, uint32_t ap) { (void)env; (void)which; (void)ap; // We don't implement ioctl for any of our file descriptors, so just // always return "not a TTY", PICO-8 doesn't seem to mind. return -PW_ENOTTY; }; uint32_t w2c_env_0x5F_0x5Fsyscall6(struct w2c_env *env, uint32_t which, uint32_t ap) { (void)which; int32_t fd = (int32_t)env_varg(env, ap, 0); if (!pw_fs_close(env->context.cart->storage, fd)) { return -pw_fs_errno(env->context.cart->storage); } return 0; } void w2c_env_0x5F_0x5Funlock(struct w2c_env *env, uint32_t ptr) { (void)env; (void)ptr; } void w2c_env_0x5Fabort(struct w2c_env *env) { (void)env; SDL_LogCritical(0, "aborting"); env_abort(); } uint32_t w2c_env_0x5Femscripten_asm_const_i(struct w2c_env *env, uint32_t code) { switch (code) { case 0: // Whether or not there is embedded cart data. Since we _always_ run // with embedded cart data, this is always 1 (i.e. true). return 1; case 1: return env->context.cart->count; case 2: { uint32_t index = env->data.cartpos / PW_CART_ROM_SIZE; uint32_t pos = env->data.cartpos++ % PW_CART_ROM_SIZE; if (index >= env->context.cart->count) { return 0; } return env->context.cart->embedded[index].rom[pos]; } case 4: if (env->data.cartname.index >= env->context.cart->count || env->data.cartname.pos >= PW_CART_NAME_MAX) { return 0; } return env->context.cart->embedded[env->data.cartname.index] .name[env->data.cartname.pos++]; case 5: // Browser history push state, no-op. return 0; case 6: // Command setup, no-op for us. return 0; case 7: // User file-system does not need to create directories, they are implicit, // so just return success. return 0; case 8: case 9: // URL contains `widget.php` or `pico-8.php` respectively, false for us. return 0; case 11: return env_swap32(&env->data.command, 0); case 12: return env_swap32(&env->data.commandp, 0); case 13: return env->data.btn = 0; case 14: if (env->data.btn < PW_PLAYERS_MAX) { return pw_input_btn(env->context.input, env->data.btn++); } else { return 0; } case 15: return pw_input_players(env->context.input); case 16: // On module load callback, no-op. return 0; case 19: case 20: // Used for writting drag and dropped PICO-8 carts. We do not support this // as a PICO-8 player, so pretend like there are none. return 0; case 25: // Request a file-system sync, handle it at the end of the frame. env->data.state.fssync = true; return 0; case 26: // The file-system is always mounted, return true. return 1; case 27: // Touch device detection, this seems to do a few things like reading mouse // coordinates from `asm_const` and making a larger audio buffer (I guess // because phones would run slower audio data request callbacks?). // TODO(nlordell): Add touch detection to `pw_input`. return 0; case 28: return (uint32_t)!(pw_input_window(env->context.input) & PW_WINDOW_VISIBLE); case 29: case 30: case 31: // All "listeners" are automatically installed in that we get them from SDL // events without asking, making these a no-op. return 0; case 33: return (uint32_t)pw_input_get_pointer_lock(env->context.input); case 34: // Whether or not `pico8_mouse` is set - since we use SDL_GetMouseState to // provide mouse updates to PICO-8, keep this as "false". return 0; case 35: { struct pw_coordinates pos; pw_input_mouse(env->context.input, &pos); return (int32_t)pos.x; } case 36: { struct pw_coordinates pos; pw_input_mouse(env->context.input, &pos); return (int32_t)pos.y; } case 37: return (uint32_t)pw_input_key(env->context.input, NULL); case 38: { int32_t key; if (!pw_input_key(env->context.input, &key)) { return -1; } return (uint32_t)key; } case 39: { int32_t dx; pw_input_wheel(env->context.input, &dx, NULL); return (uint32_t)dx; } case 40: { int32_t dy; pw_input_wheel(env->context.input, NULL, &dy); return (uint32_t)dy; } case 41: return (uint32_t)!!(pw_input_window(env->context.input) & PW_WINDOW_FOCUS); case 42: // PICO-8 keeps track of clicks on the page that are outside of the canvas // area - this does not apply to us as the whole page is outside of the // canvas and we already specify this information somewhat with the window // flags, so always return `false`. return 0; case 43: case 44: // PICO-8 uses a text area for handling clipboard events, we don't need to // do this as our SDL application handles them already; no-op. return 0; case 45: // When querying the PICO-8 mouse state this way, it expects PICO-8's // internal mouse ordering, and not SDL's, so remap it. { uint32_t result = 0; enum pw_mouse_button b = pw_input_mouse(env->context.input, NULL); if (b & PW_MOUSE_BUTTON_LEFT) { result |= 1; } if (b & PW_MOUSE_BUTTON_RIGHT) { result |= 2; } if (b & PW_MOUSE_BUTTON_MIDDLE) { result |= 4; } return result; } case 46: case 48: // Machinery for creating directories, we have implicit directories in our // file-system so these are all no-ops. return 0; case 49: env->data.state.pointerlock = false; return 0; case 50: return 0; case 51: if (!pw_input_clipboard(env->context.input, 0)) { SDL_LogWarn(0, "failed to clear clipboard: %s", SDL_GetError()); } return 0; case 53: if (!pw_input_clipboard_commit(env->context.input)) { SDL_LogWarn(0, "failed to commit to system clipboard: %s", SDL_GetError()); } // In the browser, an additional `Ctrl+C` is required to copy from the // selected text area, but not here since we write directly to the system // clipboard. Tell PICO-8 "there is no text area" so it does not print // the misleading "PRESS CTRL-C TO COMPLETE COPY" message. return 1; case 54: // We don't have a text area, so this is a no-op. return 0; case 55: { if (!pw_input_clipboard_fetch(env->context.input, &env->data.cliplen)) { SDL_LogWarn(0, "failed to fetch to system clipboard: %s", SDL_GetError()); return 0; } return (uint32_t)!!(env->data.cliplen); } default: env_badasm("i", code); } } uint32_t w2c_env_0x5Femscripten_asm_const_ii(struct w2c_env *env, uint32_t code, uint32_t a) { switch (code) { case 3: env->data.cartname.index = a; env->data.cartname.pos = 0; return 3; case 22: // Allocate the hostname, just use "localhost". AFAICT, the parameter is // always 0 and not used for anything. { char localhost[] = "localhost"; return env_strndup(env, localhost, sizeof(localhost)); } case 24: // GPIO, we implement it in case some cart uses the GPIO values as an // extra place to store data, or communicate across carts. if (a >= PW_ENV_GPIO_SIZE) { return 0; } return (uint32_t)env->data.gpio[a]; case 32: if (!pw_audio_start(env->context.audio, a)) { SDL_LogWarn(0, "failed to setup audio: %s", SDL_GetError()); } return 0; case 47: // Machinery for creating directories, we have implicit directories in our // file-system so these are all no-ops. return 0; default: env_badasm("ii", code); } } uint32_t w2c_env_0x5Femscripten_asm_const_iii(struct w2c_env *env, uint32_t code, uint32_t a, uint32_t b) { switch (code) { case 21: // System messages, does not appear to be used. Only print up to the // first 255 characters of the message. { char msg[256]; wasm_rt_memory_loada(&env->memory, a, msg, sizeof(msg)); SDL_LogDebug(0, "system message: %s", msg); return 0; } case 23: // GPIO, we implement it in case some cart uses the GPIO values as an // extra place to store data, or communicate across carts. if (a < PW_ENV_GPIO_SIZE) { env->data.gpio[a] = (uint8_t)(b & 0xff); } return 0; case 52: { char *clipboard = pw_input_clipboard(env->context.input, b); if (!clipboard) { SDL_LogWarn(0, "failed to write clipboard buffer: %s", SDL_GetError()); return 0; } wasm_rt_memory_load(&env->memory, a, clipboard, b); return 0; } case 56: if (!b) { return 0; } uint32_t len = (uint32_t)SDL_min(env->data.cliplen, b - 1); char const *clipboard = pw_input_clipboard(env->context.input, len); if (!clipboard) { SDL_LogWarn(0, "failed to read clipboard buffer: %s", SDL_GetError()); } // Make sure to not split UTF-8 characters. while (len && (clipboard[len] & 0xc0) == 0x80) { --len; } if (len) { wasm_rt_memory_store(&env->memory, a, clipboard, len); wasm_rt_memory_store8(&env->memory, a + len, 0); } return 0; default: env_badasm("iii", code); } } uint32_t w2c_env_0x5Femscripten_asm_const_iiiii(struct w2c_env *env, uint32_t code, uint32_t a, uint32_t b, uint32_t c, uint32_t d) { (void)b; (void)c; (void)d; switch (code) { case 17: // PICO-8 can ask the browser to download a file for you - it looks like // for supporting exports. We ignore them, but log them informationally; // up to the first 255 characters of the name. { char name[256]; wasm_rt_memory_loada(&env->memory, a, name, sizeof(name)); SDL_LogDebug(0, "ignoring attempt to download %s", name); return 0; } default: env_badasm("iiiii", code); } } uint32_t w2c_env_0x5Femscripten_asm_const_iiiiiii(struct w2c_env *env, uint32_t code, uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint32_t e, uint32_t f) { (void)env; (void)a; (void)b; (void)c; (void)d; (void)e; (void)f; switch (code) { 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"); return 0; default: env_badasm("iiiiiii", code); } } uint32_t w2c_env_0x5Femscripten_asm_const_iiiiiiiii( struct w2c_env *env, uint32_t code, uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint32_t e, uint32_t f, uint32_t g, uint32_t h) { (void)a; (void)b; (void)c; (void)d; (void)e; (void)g; switch (code) { case 10: // Sync PICO-8 state, we only care about requesting pointer lock (so we // can try to lock the pointer) or that shutdown is requested (so we can // exit back to the cart selectio menu. env->data.state.pointerlock = f; env->data.state.shutdown = h; return 0; default: env_badasm("iiiiiiiii", code); } } void w2c_env_0x5Femscripten_async_wget_data(struct w2c_env *env, uint32_t url, uint32_t userdata, uint32_t onload, uint32_t onerror) { (void)onload; char urlstr[256] = {0}; wasm_rt_memory_loada(&env->memory, url, urlstr, sizeof(urlstr)); // In order to fudge `LOAD("#...")` support, we implement the _bear_ // minimum `.nfo` file fetcher that just echos the `lid` back. This // makes PICO-8 attempt to load the `.p8.png` from the mounted cart // filesystem from `user_data/bbs/carts/$lid.p8.png`, enabling BBS // multicart support. static char const nfo[] = "/bbs/cpost_lister3.php?nfo=1&version=000207e&lid="; if (SDL_strstr(urlstr, nfo) == urlstr) { // Point to the `lid=...`, replace `=` with `:` for the `.nfo` // format, and then call the `onload` handler with the allocated // data buffer. char *buf = urlstr + sizeof(nfo) - 5; buf[3] = ':'; uint32_t len = SDL_strlen(buf); uint32_t data = env_strndup(env, buf, len + 1); w2c_pico8_dynCall_viii(env->context.instance, onload, userdata, data, len); w2c_pico8_0x5Ffree(env->context.instance, data); return; } SDL_LogDebug(0, "ignoring attempt to fetch %s", urlstr); w2c_pico8_dynCall_vi(env->context.instance, onerror, userdata); } uint32_t w2c_env_0x5Femscripten_get_heap_size(struct w2c_env *env) { return env->memory.size; } uint32_t w2c_env_0x5Femscripten_memcpy_big(struct w2c_env *env, uint32_t dst, uint32_t src, uint32_t len) { wasm_rt_memory_copy(&env->memory, dst, src, len); return dst; } uint32_t w2c_env_0x5Femscripten_resize_heap(struct w2c_env *env, uint32_t size) { // Don't allow heap resizing. (void)env; (void)size; return 0; } void w2c_env_0x5Femscripten_run_script(struct w2c_env *env, uint32_t src) { (void)env; (void)src; SDL_LogDebug(0, "ignoring attempt to run script on host"); } void w2c_env_0x5Femscripten_set_main_loop(struct w2c_env *env, uint32_t func, uint32_t fps, uint32_t simulate_infinite_loop) { env->data.mainloop = func; // Ignore the fps and simulate infinite loop parameters, they are always 0 // for PICO-8 anyway. (void)fps; (void)simulate_infinite_loop; } 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: %" SDL_PRIu32, code); env->data.state.shutdown = true; wasm_rt_trap(WASM_RT_TRAP_UNREACHABLE); } uint32_t w2c_env_0x5Fgmtime(struct w2c_env *env, uint32_t time) { return env_timetm(env, time, false); } uint32_t w2c_env_0x5Flocaltime(struct w2c_env *env, uint32_t time) { return env_timetm(env, time, true); } void w2c_env_0x5Flongjmp(struct w2c_env *env, uint32_t jmpbuf, uint32_t value) { struct pw_env_frame *frame = env->data.frame; if (!frame) { SDL_LogWarn(0, "attempt to longjmp without invocation handler setup"); env_abort(); } // Make sure that the value cannot be 0. value = SDL_max(value, 1); w2c_pico8_0x5FsetThrew(env->context.instance, jmpbuf, value); longjmp(frame->buf, 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. char buffer[64] = {0}; // Check that the format matches the single one we support, and it not, write // the empty string and return a written length of 0. 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; } wasm_rt_memory_check(&env->memory, tm, 44); SDL_DateTime dt = { .second = wasm_rt_memory_load32_unchecked(&env->memory, tm + 0), .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) + 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) || (uint32_t)n >= sz) { wasm_rt_memory_store8(&env->memory, buf, 0); return 0; } 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) { SDL_Time ns; if (!SDL_GetCurrentTime(&ns)) { return (uint32_t)(-1); } uint32_t s = SDL_NS_TO_SECONDS(ns); if (time) { wasm_rt_memory_store32(&env->memory, time, s); } return s; } void w2c_env_abort(struct w2c_env *env, uint32_t code) { (void)env; SDL_LogCritical(0, "aborting with code 0x%08x", code); env_abort(); } uint32_t w2c_env_abortOnCannotGrowMemory(struct w2c_env *env, uint32_t size) { (void)env; SDL_LogCritical(0, "aborting unable to grow memory to size %u", size); env_abort(); } uint32_t w2c_env_getTempRet0(struct w2c_env *env) { return env->data.tempret; } void w2c_env_invoke_vii(struct w2c_env *env, uint32_t fn, uint32_t a, uint32_t b) { struct pw_env_frame frame = { .parent = env->data.frame, }; uint32_t sp = w2c_pico8_stackSave(env->context.instance); env->data.frame = &frame; if (!setjmp(frame.buf)) { w2c_pico8_dynCall_vii(env->context.instance, fn, a, b); } else { // Stack unwinding - restore the stack pointer. w2c_pico8_stackRestore(env->context.instance, sp); w2c_pico8_0x5FsetThrew(env->context.instance, 1, 0); } env->data.frame = frame.parent; } void w2c_env_setTempRet0(struct w2c_env *env, uint32_t value) { env->data.tempret = value; } static struct w2c_global shared_global = { .infinity = INFINITY, .nan = NAN, }; double *w2c_global_Infinity(struct w2c_global *global) { if (!global) { global = &shared_global; } return &global->infinity; } double *w2c_global_NaN(struct w2c_global *global) { if (!global) { global = &shared_global; } return &global->nan; }