Commit 1aaa5fee

1aaa5feed711Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

fix(runtime): File.read uses text mode so CRLF→LF round-trips correctly

sp_file_read opened files with "rb" (binary mode), so on Windows a file written via File.write (text mode, LF→CRLF on write) read back the raw \r\n. Passing that content through puts then sent it to stdout (also text mode), which only translated the trailing \n, producing \r\r\n on the wire. CRuby's File.read on Windows is text mode, so the round-trip cancels and stdout sees plain \n.

Switching sp_file_read to "r" matches CRuby. Linux is unaffected because text and binary modes are identical there.

Also drives null-termination by fread's actual byte count instead of ftell's raw-file size, which can over-count under text mode.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
1aaa5feed711
Parent
1f18075f73b3

lib/sp_runtime.hmodifiedView file

@@ -776,7 +776,14 @@
776776 static volatile int sp_catch_top = 0;
777777 static void sp_throw(const char *tag, mrb_int val) { int i = sp_catch_top - 1; while (i >= 0) { if (strcmp(sp_catch_tag[i], tag) == 0) { sp_catch_val[i] = val; sp_catch_top = i + 1; longjmp(sp_catch_stack[i], 1); } i--; } fprintf(stderr, "uncaught throw: %s\n", tag); exit(1); }
778778
779-static const char *sp_file_read(const char *path) { FILE *f = fopen(path, "rb"); if (!f) return &("\xff" "")[1]; fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET); char *buf = sp_str_alloc(sz); if (sz > 0) { size_t r = fread(buf, 1, sz, f); (void)r; } buf[sz] = 0; fclose(f); return buf; }
779+/* Text mode ("r") matches CRuby's File.read: on Windows, CRLF is
780+ normalized to LF on read, which cancels out fopen("w")'s
781+ LF→CRLF on write. Without this, content from File.read passed to
782+ puts goes through stdout's text-mode translation a second time
783+ and `\r\n` becomes `\r\r\n`. fread's actual byte count drives
784+ null-termination because text mode shrinks the byte count below
785+ ftell's raw-file size. */
786+static const char *sp_file_read(const char *path) { FILE *f = fopen(path, "r"); if (!f) return &("\xff" "")[1]; fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET); char *buf = sp_str_alloc(sz); size_t n = 0; if (sz > 0) { n = fread(buf, 1, sz, f); } buf[n] = 0; fclose(f); return buf; }
780787 static void sp_file_write(const char *path, const char *data) { FILE *f = fopen(path, "w"); if (f) { fputs(data, f); fclose(f); } }
781788 static mrb_bool sp_file_exist(const char *path) { FILE *f = fopen(path, "r"); if (f) { fclose(f); return TRUE; } return FALSE; }
782789 static void sp_file_delete(const char *path) { remove(path); }