authorgravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2022-11-30 01:26:25-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-12-06 12:15:04-07:00
loge000db278295e6ca61e1d078ae32f83a9abca6da
treea5b4984b0a87c1cecf55576eaf314cd2486f956e
parent12633467747de2349f7cc0f5068e9749801476b0

wasi: implement file truncation

The way this is implemented destroys the contents of the file, so revisit if this causes issues in the future.

1 files changed, 11 insertions(+), 4 deletions(-)

stage1/wasi.c+11-4
...@@ -555,10 +555,17 @@ uint32_t wasi_snapshot_preview1_fd_filestat_set_size(uint32_t fd, uint64_t size)...@@ -555,10 +555,17 @@ uint32_t wasi_snapshot_preview1_fd_filestat_set_size(uint32_t fd, uint64_t size)
555 if (fseek(fds[fd].stream, 0, SEEK_END) < 0) return wasi_errno_io;555 if (fseek(fds[fd].stream, 0, SEEK_END) < 0) return wasi_errno_io;
556 long old_size = ftell(fds[fd].stream);556 long old_size = ftell(fds[fd].stream);
557 if (old_size < 0) return wasi_errno_io;557 if (old_size < 0) return wasi_errno_io;
558 if (size > (unsigned long)old_size) {558 if (size != (unsigned long)old_size) {
559 if (fseek(fds[fd].stream, size - 1, SEEK_SET) < 0) return wasi_errno_io;559 if (size > 0 && fseek(fds[fd].stream, size - 1, SEEK_SET) < 0) return wasi_errno_io;
560 fputc(0, fds[fd].stream);560 if (size < (unsigned long)old_size) {
561 } else if (size < (unsigned long)old_size) panic("unimplemented");561 // Note that this destroys the contents on resize might have to save truncated
562 // file in memory if this becomes an issue.
563 FILE *trunc = fopen(des[fds[fd].de].host_path, "wb");
564 if (trunc == NULL) return wasi_errno_io;
565 fclose(trunc);
566 }
567 if (size > 0) fputc(0, fds[fd].stream);
568 }
562 if (fsetpos(fds[fd].stream, &pos) < 0) return wasi_errno_io;569 if (fsetpos(fds[fd].stream, &pos) < 0) return wasi_errno_io;
563 return wasi_errno_success;570 return wasi_errno_success;
564}571}