aboutsummaryrefslogtreecommitdiff
path: root/src/fs.c
blob: 77b34ee033be1b9a99ce3f8192c1fe2f05e2a173 (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
#include <SDL3/SDL_error.h>
#include <SDL3/SDL_filesystem.h>
#include <SDL3/SDL_log.h>

#include "fs.h"
#include "path.h"
#include "sysroot.h"
#include "tar.h"

#define BUFFER_SIZE 1024

static uint8_t empty_bytes[] = {0};

static bool init_output(union pw_fs_node *node) {
  node->w.type = PW_FS_NODE_OUTPUT;
  node->w.data = SDL_malloc(BUFFER_SIZE);
  if (!node->w.data) {
    return false;
  }
  node->w.size = 0;
  node->w.capacity = BUFFER_SIZE;
  return true;
}

static int cmp_entry(void const *a, void const *b) {
  struct pw_fs_entry const *const *ea = a;
  struct pw_fs_entry const *const *eb = b;
  return SDL_strcmp((*ea)->path, (*eb)->path);
}

static bool append_entry(struct pw_fs_mount *m, struct pw_fs_entry *e) {
  while (m->count >= m->capacity) {
    size_t capacity = SDL_max(m->capacity, 16) * 2;
    if (capacity < m->capacity) {
      return SDL_OutOfMemory();
    }

    void *entries = SDL_realloc(m->entries, capacity * sizeof(*m->entries));
    if (!entries) {
      return SDL_OutOfMemory();
    }

    m->entries = entries;
    m->capacity = capacity;
  }

  m->entries[m->count++] = e;
  return true;
}

static void sort_entries(struct pw_fs_mount *m) {
  SDL_qsort(m->entries, m->count, sizeof(*m->entries), cmp_entry);
}

static void free_entry(struct pw_fs_entry *e) {
  union pw_fs_node *n = &e->node;
  switch (n->type) {
  case PW_FS_NODE_BUFFER:
  case PW_FS_NODE_OUTPUT:
    SDL_free(n->w.data);
    break;
  default:
    break;
  }
  SDL_free(e);
}

static void free_entries(struct pw_fs_mount *m) {
  for (size_t i = 0; i < m->count; ++i) {
    free_entry(m->entries[i]);
  }
  SDL_free(m->entries);
}

static bool normalize_path(char const **path) {
  if (!*path) {
    return false;
  }
  while (**path == '/') {
    ++(*path);
  }
  return **path;
}

struct pw_fs *pw_fs_init(char const *path) {
  struct pw_tar *tar = NULL;
  struct pw_fs *fs = SDL_calloc(1, sizeof(*fs));
  if (!fs) {
    return NULL;
  }

  if (path) {
    fs->path = SDL_strdup(path);
    if (!fs->path) {
      goto error;
    }
  }

  fs->root.entries = SDL_malloc(32 * sizeof(*fs->root.entries));
  if (!fs->root.entries) {
    goto error;
  }
  fs->root.capacity = 32;

  {
    struct pw_fs_entry *datapod = SDL_calloc(1, sizeof(*datapod));
    if (!datapod) {
      goto error;
    }

    SDL_strlcpy(datapod->path, "data.pod", PW_FS_PATH_MAX);
    datapod->node.r.type = PW_FS_NODE_STATIC;
    datapod->node.r.data = pw_sysroot_pico8_data_pod.data;
    datapod->node.r.size = pw_sysroot_pico8_data_pod.size;

    if (!append_entry(&fs->root, datapod)) {
      goto error;
    }
  }

  if (path) {
    tar = pw_tar_open(path, PW_TAR_OPEN_READ);
  }
  if (tar) {
    bool ok;
    for (;;) {
      struct pw_tar_entry f;
      if (!pw_tar_read(tar, &f)) {
        ok = false;
        break;
      }

      if (!f.data) {
        ok = true;
        break;
      }

      const char *p = f.path;
      if (!normalize_path(&p)) {
        SDL_free(f.data);
        ok = false;
        break;
      }

      struct pw_fs_entry *e = SDL_calloc(1, sizeof(*e));
      if (!e) {
        SDL_free(f.data);
        goto error;
      }

      size_t n = SDL_strlcpy(e->path, p, PW_FS_PATH_MAX);
      if (n >= PW_FS_PATH_MAX) {
        SDL_SetError("file path too long '%s'", p);
        SDL_free(f.data);
        SDL_free(e);
        ok = false;
        break;
      }

      if (!append_entry(&fs->root, e)) {
        SDL_free(f.data);
        SDL_free(e);
        goto error;
      }

      e->node.type = PW_FS_NODE_BUFFER;
      e->node.w.data = f.data;
      e->node.w.size = f.size;
      e->node.w.capacity = f.capacity;
    }

    if (ok) {
      sort_entries(&fs->root);
    } else {
      SDL_LogWarn(0, "could not read cart storage: %s", SDL_GetError());

      // Free the loaded entries, if any - since we don't know whether or not
      // they should be there.
      for (size_t i = 1; i < fs->root.count; ++i) {
        free_entry(fs->root.entries[i]);
      }
      fs->root.count = 1;

      // In case the Tar is corrupt, do not clobber it with an empty tar
      // and fallback to in-memory cart storage.
      SDL_free(fs->path);
      fs->path = NULL;
    }

    pw_tar_free(tar);
    tar = NULL;

    fs->dirty = false;
  } else if (path && SDL_GetPathInfo(path, NULL)) {
    SDL_LogWarn(0, "cannot access cart storage: %s", SDL_GetError());

    // In case the Tar file exists but we cannot access it, fall back to
    // in-memory cart storage and prevent writing over the file.
    SDL_free(fs->path);
    fs->path = NULL;

    fs->dirty = false;
  } else if (path) {
    SDL_LogDebug(0, "initializing cart storage");
    fs->dirty = true;
  } else {
    SDL_LogDebug(0, "using in-memory cart storage");
  }

  fs->dev.in.r.type = PW_FS_NODE_STATIC;
  fs->dev.in.r.data = empty_bytes;
  fs->dev.in.r.size = 0;
  if (!init_output(&fs->dev.out) || !init_output(&fs->dev.err)) {
    goto error;
  }
  fs->streams[0].node = &fs->dev.in;
  fs->streams[0].flags = PW_FS_STREAM_READ;
  fs->streams[1].node = &fs->dev.out;
  fs->streams[1].flags = PW_FS_STREAM_WRITE | PW_FS_STREAM_APPEND;
  fs->streams[2].node = &fs->dev.err;
  fs->streams[2].flags = PW_FS_STREAM_WRITE | PW_FS_STREAM_APPEND;

  return fs;

error:
  if (tar) {
    pw_tar_free(tar);
  }
  if (fs->root.entries) {
    free_entries(&fs->root);
  }
  if (fs->dev.out.w.data) {
    SDL_free(fs->dev.out.w.data);
  }
  if (fs->dev.err.w.data) {
    SDL_free(fs->dev.err.w.data);
  }
  if (fs->path) {
    SDL_free(fs->path);
  }
  SDL_free(fs);
  return NULL;
}

void pw_fs_free(struct pw_fs *fs) {
  if (!fs) {
    SDL_InvalidParamError("fs");
    return;
  }

  if (fs->root.entries) {
    free_entries(&fs->root);
  }
  SDL_free(fs->dev.out.w.data);
  SDL_free(fs->dev.err.w.data);

  if (fs->path) {
    SDL_free(fs->path);
  }
  SDL_free(fs);
}

bool pw_fs_sync(struct pw_fs *fs) {
  if (!fs) {
    return SDL_InvalidParamError("fs");
  }

  // Check if we are using disk-backed storage and if the virtual file-system
  // is dirty and needs to be written.
  if (!fs->path || !fs->dirty) {
    fs->dirty = false;
    return true;
  }

  // Currently, we re-write the entire archive every time we sync it
  // to the file-system. This is a bit wasteful (and can wear storage
  // devices). That being said, the "dirty" flag paired with the fact
  // that PICO-8 does not seem to write often to disk and this tar is
  // typically quite small, makes this acceptable for now. Log that we
  // are writing to disk to keep an eye on how often it happens.
  SDL_LogDebug(0, "writing cart storage to disk %s", fs->path);

  bool ok = false;
  char *tmp = NULL;
  struct pw_tar *tar = NULL;

  int n = SDL_asprintf(&tmp, "%s.sync", fs->path);
  if (n < 0) {
    goto cleanup;
  }

  tar = pw_tar_open(tmp, PW_TAR_OPEN_WRITE);
  if (!tar) {
    goto cleanup;
  }

  for (size_t i = 0; i < fs->root.count; ++i) {
    struct pw_fs_entry *e = fs->root.entries[i];

    // Only persist `user_data` files written by PICO-8.
    if (e->node.type != PW_FS_NODE_BUFFER ||
        SDL_memcmp(e->path, "user_data/", 10)) {
      continue;
    }

    struct pw_fs_node_buffer *w = &e->node.w;
    if (!pw_tar_write(tar, e->path, w->data, w->size)) {
      goto cleanup;
    }
  }

  // Write the "end-of-archive" block.
  if (!pw_tar_write(tar, "", NULL, 0)) {
    goto cleanup;
  }

  // Move our new storage into place. Note that `SDL_RenamePath` is not
  // guaranteed to be atomic, so there is technically some chance for
  // dataloss here, but in practice it should not be an issue.
  if (SDL_RenamePath(tmp, fs->path)) {
    fs->dirty = false;
    ok = true;
  }

cleanup:
  if (tar) {
    pw_tar_free(tar);
  }
  if (!ok) {
    // Unfortunately, removing a path sets an error if the path does not
    // exist, which would hide the true error that got us here. Do the
    // best we can to copy the error and restore it after trying to clean
    // up our temporary file.
    char err[1024];
    SDL_strlcpy(err, SDL_GetError(), sizeof(err));
    SDL_RemovePath(tmp);
    SDL_SetError("%s", err);
  }
  if (tmp) {
    SDL_free(tmp);
  }
  return ok;
}

static int cmp_path(void const *a, void const *b) {
  char const *path = a;
  struct pw_fs_entry const *const *entry = b;
  return SDL_strcmp(path, (*entry)->path);
}

static char const cart_dir[] = "user_data/carts/";

static int cmp_cart_path(void const *a, void const *b) {
  char const *cart = a;
  struct pw_fs_entry const *const *entry = b;

  char const *path = (*entry)->path;
  if (SDL_strstr(path, cart_dir) == path) {
    return SDL_strcmp(cart, path + sizeof(cart_dir) - 1);
  } else {
    return SDL_strcmp(cart_dir, path);
  }
}

static struct pw_fs_entry *find_entry(struct pw_fs *fs, char const *path,
                                      bool absolute) {
  struct pw_fs_entry **e = SDL_bsearch(path, fs->root.entries, fs->root.count,
                                       sizeof(*fs->root.entries), cmp_path);

  // Under some conditions, PICO-8 will `LOAD("CART.P8")` by opening a file
  // instead of using the embedded cart. To support this, for relative cart
  // paths look in the `user_data/carts/` directory if we didn't find the
  // file under root.
  if (!e && !absolute &&
      (pw_hasext(path, ".p8") || pw_hasext(path, ".p8.png"))) {
    e = SDL_bsearch(path, fs->root.entries, fs->root.count,
                    sizeof(*fs->root.entries), cmp_cart_path);
  }

  if (!e) {
    return NULL;
  }
  return *e;
}

static struct pw_fs_entry *create_entry(struct pw_fs *fs, char const *path) {
  struct pw_fs_entry *e = SDL_calloc(1, sizeof(*e));
  if (!e) {
    fs->err = PW_ENOMEM;
    return NULL;
  }

  size_t n = SDL_strlcpy(e->path, path, PW_FS_PATH_MAX);
  if (n >= PW_FS_PATH_MAX) {
    fs->err = PW_EINVAL;
    SDL_InvalidParamError("path");
    goto error;
  }

  e->node.w.type = PW_FS_NODE_BUFFER;
  e->node.w.data = SDL_malloc(BUFFER_SIZE);
  if (!e->node.w.data) {
    fs->err = PW_ENOMEM;
    goto error;
  }
  e->node.w.size = 0;
  e->node.w.capacity = BUFFER_SIZE;

  if (!append_entry(&fs->root, e)) {
    fs->err = PW_ENOMEM;
    goto error;
  }
  sort_entries(&fs->root);

  // We added a new file, mark the file-system as dirty to ensure a new Tar
  // entry gets created for our new file.
  fs->dirty = true;

  return e;

error:
  if (e->node.w.data) {
    SDL_free(e->node.w.data);
  }
  SDL_free(e);
  return NULL;
}

bool pw_fs_open(struct pw_fs *fs, char const *path, enum pw_fs_open_flag flags,
                pw_fd *fd) {
  char const *rawpath = path;

  if (!fs) {
    return SDL_InvalidParamError("fs");
  }
  if (!normalize_path(&path)) {
    fs->err = PW_EINVAL;
    return SDL_InvalidParamError("path");
  }
  if (!fd) {
    fs->err = PW_EINVAL;
    return SDL_InvalidParamError("fd");
  }
  if (flags & PW_O_DIRECTORY) {
    fs->err = PW_ENOTDIR;
    return SDL_InvalidParamError("flags");
  }

  int32_t f = 0;
  for (; f < PW_FS_STREAM_MAX && fs->streams[f].node; ++f) {
  }
  if (f >= PW_FS_STREAM_MAX) {
    fs->err = PW_EMFILE;
    return SDL_SetError("too many open files");
  }

  struct pw_fs_stream *s = &fs->streams[f];
  switch (flags & PW_O_ACCMODE) {
  case PW_O_RDONLY:
    if (flags & PW_O_TRUNC) {
      fs->err = PW_EINVAL;
      return SDL_InvalidParamError("flags");
    }
    s->flags = PW_FS_STREAM_READ;
    break;
  case PW_O_WRONLY:
    s->flags = PW_FS_STREAM_WRITE;
    break;
  case PW_O_RDWR:
    s->flags = PW_FS_STREAM_READ | PW_FS_STREAM_WRITE;
    break;
  default:
    fs->err = PW_EINVAL;
    return SDL_InvalidParamError("flags");
  }
  if (flags & PW_O_APPEND) {
    s->flags |= PW_FS_STREAM_APPEND;
  }

  bool absolute = path != rawpath;
  struct pw_fs_entry *e = find_entry(fs, path, absolute);
  if (e && (flags & PW_O_CREAT) && (flags & PW_O_EXCL)) {
    fs->err = PW_EEXIST;
    return SDL_SetError("file already exists");
  }
  if (!e && !(flags & PW_O_CREAT)) {
    fs->err = PW_ENOENT;
    return SDL_SetError("file does not exist");
  }
  if (e && e->node.type == PW_FS_NODE_STATIC &&
      (s->flags & PW_FS_STREAM_WRITE)) {
    fs->err = PW_EACCES;
    return SDL_SetError("cannot modify read-only file");
  }
  if (e && e->node.type == PW_FS_NODE_OUTPUT &&
      (s->flags & PW_FS_STREAM_READ)) {
    fs->err = PW_EACCES;
    return SDL_SetError("cannot read write-only file");
  }

  if (!e && !(e = create_entry(fs, path))) {
    return false;
  }

  s->node = &e->node;
  s->pos = 0;
  if (flags & PW_O_TRUNC) {
    // Make sure that our truncation persists to disk for files.
    if (e->node.type == PW_FS_NODE_BUFFER) {
      fs->dirty = true;
    }
    e->node.w.size = 0;
  }

  *fd = f;
  return true;
}

#define PW_S_IFCHR 0020000
#define PW_S_IFREG 0100000

bool pw_fs_stat(struct pw_fs *fs, char const *path, struct pw_fs_stat *stat) {
  char const *rawpath = path;

  if (!fs) {
    return SDL_InvalidParamError("fs");
  }
  if (!normalize_path(&path)) {
    fs->err = PW_EINVAL;
    return SDL_InvalidParamError("path");
  }
  if (!stat) {
    fs->err = PW_EINVAL;
    return SDL_InvalidParamError("stat");
  }

  bool absolute = path != rawpath;
  struct pw_fs_entry *e = find_entry(fs, path, absolute);
  if (!e) {
    fs->err = PW_ENOENT;
    return SDL_SetError("file does not exist");
  }

  switch (e->node.type) {
  case PW_FS_NODE_STATIC:
    stat->mode = PW_S_IFCHR | 0444;
    stat->size = 0;
    break;
  case PW_FS_NODE_BUFFER:
    stat->mode = PW_S_IFREG | 0666;
    stat->size = (uint64_t)SDL_min(e->node.w.size, UINT64_MAX);
    break;
  case PW_FS_NODE_OUTPUT:
    stat->mode = PW_S_IFCHR | 0222;
    stat->size = 0;
    break;
  default:
    fs->err = PW_ENOENT;
    return false;
  }

  return true;
}

static struct pw_fs_stream *get_stream(struct pw_fs *fs, pw_fd fd) {
  if (!fs) {
    SDL_InvalidParamError("fs");
    return NULL;
  }
  if (fd < 0 || fd >= PW_FS_STREAM_MAX || !fs->streams[fd].node) {
    fs->err = PW_EBADF;
    SDL_InvalidParamError("fd");
    return NULL;
  }

  return &fs->streams[fd];
}

bool pw_fs_close(struct pw_fs *fs, pw_fd fd) {
  struct pw_fs_stream *s = get_stream(fs, fd);
  if (!s) {
    return false;
  }

  bool result = true;

  // We have some special handing for output streams (i.e. stdout and
  // stderr) where we write a final log message in case there are
  // pending bytes, even without a newline.
  if (s->node->type == PW_FS_NODE_OUTPUT && s->node->w.size) {
    if (s->node->w.data[s->node->w.size - 1] != '\n') {
      uint8_t *buffer = pw_fs_write(fs, fd, 1);
      if (!buffer) {
        result = false;
        goto close;
      }
      *buffer = '\n';
    }
    result = pw_fs_flush(fs, fd);
  }

close:
  SDL_zerop(s);
  return result;
}

bool pw_fs_seek(struct pw_fs *fs, pw_fd fd, int64_t offset,
                enum pw_fs_seek_whence whence, int64_t *newpos) {
  struct pw_fs_stream *s = get_stream(fs, fd);
  if (!s) {
    return false;
  }

  size_t size;
  switch (s->node->type) {
  case PW_FS_NODE_STATIC:
    size = s->node->r.size;
    break;
  case PW_FS_NODE_BUFFER:
  case PW_FS_NODE_OUTPUT:
    size = s->node->w.size;
    break;
  default:
    fs->err = PW_EBADF;
    return SDL_SetError("cannot read from write-only file entry");
  }

  size_t pos;
  switch (whence) {
  case PW_SEEK_SET:
    pos = 0;
    break;
  case PW_SEEK_CUR:
    pos = s->pos;
    break;
  case PW_SEEK_END:
    pos = size;
    break;
  default:
    fs->err = PW_EINVAL;
    return SDL_InvalidParamError("whence");
  }

  if (offset > 0) {
    uint64_t uoffset = (uint64_t)offset;
    if (uoffset > SIZE_MAX - pos) {
      fs->err = PW_EINVAL;
      return SDL_InvalidParamError("offset");
    }
    pos += (size_t)uoffset;
  } else if (offset < 0) {
    uint64_t uoffset = -(uint64_t)offset;
    if (uoffset > pos) {
      fs->err = PW_EINVAL;
      return SDL_InvalidParamError("offset");
    }
    pos -= (size_t)uoffset;
  }

  // This is a little weird - but the final position needs to fit in
  // a signed 64-bit value (even if we use unsigned `size_t` values
  // internally). In practice, this should not matter.
  if (pos > INT64_MAX) {
    fs->err = PW_EOVERFLOW;
    return SDL_SetError("seek overflows PICO-8 maximum position");
  }

  s->pos = pos;
  if (newpos) {
    *newpos = (int64_t)pos;
  }

  return true;
}

bool pw_fs_cntl(struct pw_fs *fs, pw_fd fd, enum pw_fs_cntl_op op,
                int32_t *arg) {
  struct pw_fs_stream *s = get_stream(fs, fd);
  if (!s) {
    return false;
  }
  if (!arg) {
    fs->err = PW_EINVAL;
    return false;
  }

  switch (op) {
  case PW_F_GETFL: {
    enum pw_fs_open_flag f;
    if (s->flags & PW_FS_STREAM_READ && s->flags & PW_FS_STREAM_WRITE) {
      f = PW_O_RDWR;
    } else if (s->flags & PW_FS_STREAM_READ) {
      f = PW_O_RDONLY;
    } else if (s->flags & PW_FS_STREAM_WRITE) {
      f = PW_O_WRONLY;
    } else {
      fs->err = PW_EBADF;
      return SDL_SetError("invalid file stream flags");
    }
    if (s->flags & PW_FS_STREAM_APPEND) {
      f |= PW_O_APPEND;
    }

    *arg = (int32_t)f;
    return true;
  }
  case PW_F_SETFL:
    if (*arg & PW_O_APPEND) {
      s->flags |= PW_FS_STREAM_APPEND;
    } else {
      s->flags &= ~PW_FS_STREAM_APPEND;
    }

    *arg = 0;
    return true;
  default:
    fs->err = PW_EINVAL;
    return SDL_SetError("invalid file descriptor operation %d", op);
  }
}

uint8_t const *pw_fs_read(struct pw_fs *fs, pw_fd fd, uint32_t len,
                          uint32_t *sz) {
  struct pw_fs_stream *s = get_stream(fs, fd);
  if (!s) {
    return NULL;
  }
  if (!sz) {
    SDL_InvalidParamError("sz");
    return NULL;
  }

  if (!(s->flags & PW_FS_STREAM_READ)) {
    fs->err = PW_EBADF;
    SDL_SetError("cannot read from write-only file stream");
    return NULL;
  }

  uint8_t const *data;
  size_t size;
  switch (s->node->type) {
  case PW_FS_NODE_STATIC:
    data = s->node->r.data;
    size = s->node->r.size;
    break;
  case PW_FS_NODE_BUFFER:
    data = s->node->w.data;
    size = s->node->w.size;
    break;
  default:
    fs->err = PW_EBADF;
    SDL_SetError("cannot read from write-only file entry");
    return NULL;
  }

  // In case we seeked past the end of the file, read nothing.
  if (s->pos >= size) {
    *sz = 0;
    return data + size;
  }

  size_t end = s->pos + (size_t)len;
  if (end < s->pos) {
    end = SIZE_MAX;
  }
  end = SDL_min(end, size);

  uint8_t const *buffer = data + s->pos;
  *sz = end - s->pos;

  s->pos = end;
  return buffer;
}

uint8_t *pw_fs_write(struct pw_fs *fs, pw_fd fd, uint32_t len) {
  struct pw_fs_stream *s = get_stream(fs, fd);
  if (!s) {
    return NULL;
  }

  if (!(s->flags & PW_FS_STREAM_WRITE)) {
    fs->err = PW_EBADF;
    SDL_SetError("cannot write to read-only file stream");
    return NULL;
  }

  struct pw_fs_node_buffer *w;
  switch (s->node->type) {
  case PW_FS_NODE_BUFFER:
  case PW_FS_NODE_OUTPUT:
    w = &s->node->w;
    break;
  default:
    fs->err = PW_EBADF;
    SDL_SetError("cannot write to read-only file entry");
    return NULL;
  }

  // With the append flag, always move to the end of the file. This
  // matters when there are multiple file descriptors writing to the
  // same file.
  if (s->flags & PW_FS_STREAM_APPEND) {
    s->pos = w->size;
  }

  // If we write 0 bytes, just return right away, as we do not want
  // to resize the buffer in case we have seeked past EOF.
  if (!len) {
    return w->data + w->capacity;
  }

  size_t end = s->pos + (size_t)len;
  if (end < s->pos) {
    fs->err = PW_EFBIG;
    SDL_SetError("write past maximum file size");
    return NULL;
  }

  // Check if we need to grow our buffer.
  if (end > w->capacity) {
    size_t capacity = SDL_max(w->capacity * 2, end);
    uint8_t *data = SDL_realloc(w->data, capacity);
    if (!data) {
      fs->err = PW_EFBIG;
      return NULL;
    }

    w->data = data;
    w->capacity = capacity;
  }

  // We cannot know for sure that the caller will actually write the
  // data to the buffer, which means that it is possible for us to sync
  // uninitialized malloc data which would be undefined behaviour. To
  // prevent this, always clear the new portions of the buffer. Note that
  // POSIX requires holes to be filled with 0s (in case the file was
  // seeked past the end), so we satisfy that as well.
  if (end > w->size) {
    SDL_memset(w->data + w->size, 0, end - w->size);
  }

  uint8_t *buffer = w->data + s->pos;
  w->size = SDL_max(w->size, end);
  s->pos = end;

  // In case we are writting to a file's buffer, and not just to stdout
  // or stderr, make the file system as dirty.
  if (w->type == PW_FS_NODE_BUFFER) {
    fs->dirty = true;
  }

  return buffer;
}

bool pw_fs_flush(struct pw_fs *fs, pw_fd fd) {
  struct pw_fs_stream *s = get_stream(fs, fd);
  if (!s) {
    return false;
  }

  struct pw_fs_node_buffer *b;
  switch (s->node->type) {
  case PW_FS_NODE_OUTPUT:
    b = &s->node->w;
    break;
  default:
    return true;
  }

  char marker;
  switch (fd) {
  case 1:
    marker = '.';
    break;
  case 2:
    marker = '!';
    break;
  default:
    marker = '?';
    break;
  }

  size_t offset = 0;
  for (size_t i = 0; i < b->size; ++i) {
    if (b->data[i] != '\n') {
      continue;
    }

    b->data[i] = '\0';
    SDL_LogDebug(0, "PICO-8>%c %s", marker, b->data + offset);
    offset = i + 1;
  }

  b->size -= offset;
  if (offset && b->size) {
    SDL_memmove(b->data, b->data + offset, b->size);
  }

  return true;
}

enum pw_fs_errno pw_fs_errno(struct pw_fs *fs) {
  if (!fs) {
    SDL_InvalidParamError("fs");
    return PW_EOK;
  }

  return fs->err;
}