aboutsummaryrefslogtreecommitdiff
path: root/src/env.c
blob: 011366521a96c9f272c8e625ebb17e5ba4ce47af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
#include <math.h>

#include <SDL3/SDL_error.h>
#include <SDL3/SDL_log.h>
#include <SDL3/SDL_stdinc.h>
#include <SDL3/SDL_time.h>
#include <SDL3/SDL_timer.h>

#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_start(struct w2c_env *env) {
  if (!env) {
    return SDL_InvalidParamError("env");
  }

  struct wasm_rt_trap_handler_t handler;
  if (!wasm_rt_trap_register(&handler)) {
    return false;
  }

  if (wasm_rt_trapped(&handler)) {
    return SDL_SetError("PICO-8 startup execution trapped: %s",
                        wasm_rt_trap_str(handler.code));
  }

  w2c_pico8_0x5F_0x5Femscripten_environ_constructor(env->context.instance);

  char const *args[] = {"./picow", "-run"};
  uint32_t argv = w2c_pico8_stackAlloc(
      env->context.instance, (SDL_arraysize(args) + 1) * sizeof(uint32_t));
  wasm_rt_memory_store32(&env->memory,
                         argv + SDL_arraysize(args) * sizeof(uint32_t), 0);
  for (size_t i = 0; i < SDL_arraysize(args); ++i) {
    uint32_t sz = (uint32_t)SDL_strlen(args[i]) + 1;
    uint32_t arg = w2c_pico8_stackAlloc(env->context.instance, sz);
    wasm_rt_memory_store(&env->memory, arg, args[i], sz);
    wasm_rt_memory_store32(&env->memory, argv + i * sizeof(arg), arg);
  }

  uint32_t status =
      w2c_pico8_0x5Fmain(env->context.instance, SDL_arraysize(args), argv);

  wasm_rt_trap_unregister();

  if (status) {
    return SDL_SetError("main returned exit code");
  }
  if (!env->data.mainloop) {
    return SDL_SetError("cannot continue without main loop set");
  }

  return true;
}

static bool env_shutdown(struct w2c_env *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;
}

bool pw_env_iterate(struct w2c_env *env, bool *shutdown) {
  if (!env || env_shutdown(env)) {
    return SDL_InvalidParamError("env");
  }
  if (!shutdown) {
    return SDL_InvalidParamError("shutdown");
  }

  struct wasm_rt_trap_handler_t handler;
  if (!wasm_rt_trap_register(&handler)) {
    return false;
  }

  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.
    env->data.frame = NULL;

    // In case we trapped for an `_exit` call, treat it as a shutdown
    // request instead of a trap.
    if (env_shutdown(env)) {
      *shutdown = true;
      return true;
    }

    return SDL_SetError("PICO-8 iteration execution trapped: %s",
                        wasm_rt_trap_str(handler.code));
  }

  w2c_pico8_dynCall_v(env->context.instance, env->data.mainloop);

  if (pw_audio_ready(env->context.audio)) {
    uint32_t len;
    int16_t *data = pw_audio_lock(env->context.audio, &len);
    if (!data) {
      SDL_LogWarn(0, "unable to lock audio device: %s", SDL_GetError());
      goto mixdone;
    }
    if (!len) {
      goto mixdone;
    }

    uint32_t samples = w2c_pico8_0x5Fmix_0(env->context.instance, len, len);
    wasm_rt_memory_load16v(&env->memory, samples, (uint16_t *)data, len);
    if (!pw_audio_unlock(env->context.audio)) {
      SDL_LogWarn(0, "unable to unlock audio device: %s", SDL_GetError());
      goto mixdone;
    }
  }
mixdone:

  wasm_rt_trap_unregister();

  *shutdown = env_shutdown(env);

  bool pointerlock;
  bool fssync;
  if (*shutdown) {
    // Always reset pointer lock and sync storage on shutdown.
    pointerlock = false;
    fssync = true;
  } else {
    pointerlock = env->data.state.pointerlock;
    env->data.state.pointerlock = false;
    fssync = env->data.state.fssync;
    env->data.state.fssync = false;
  }
  if (!pw_input_set_pointer_lock(env->context.input, pointerlock)) {
    SDL_LogWarn(0, "failed to set pointer lock: %s", SDL_GetError());
  }
  if (fssync && !pw_fs_sync(env->context.cart->storage)) {
    SDL_LogWarn(0, "failed to persist user storage: %s", SDL_GetError());
  }
  if (*shutdown && !pw_audio_stop(env->context.audio)) {
    SDL_LogWarn(0, "failed to stop audio: %s", SDL_GetError());
  }

  return true;
}

/**
 * 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;
}