Commit 540115ed

540115eddca2Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 7 files · +6 added · ~1 modified

Description

Merge pull request #568 from ydah/fix-file-directory-io-errors

fix(runtime): raise Errno::EISDIR for directory file I/O

Details

Commit
540115eddca2
Parent
707e0553ba9e
Merge parent
61c4e3b0ef23

lib/sp_runtime.hmodifiedView file

@@ -1751,8 +1751,35 @@
17511751 and `\r\n` becomes `\r\r\n`. fread's actual byte count drives
17521752 null-termination because text mode shrinks the byte count below
17531753 ftell's raw-file size. */
1754-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; }
1755-static void sp_file_write(const char *path, const char *data) { FILE *f = fopen(path, "wb"); if (f) { fwrite(data, 1, sp_str_byte_len(data), f); fclose(f); } }
1754+static const char *sp_file_read(const char *path) {
1755+ if (sp_file_directory(path)) {
1756+ sp_raise_cls("Errno::EISDIR", sp_sprintf("Is a directory @ io_fread - %s", path));
1757+ }
1758+ FILE *f = fopen(path, "r");
1759+ if (!f) return &("\xff" "")[1];
1760+ fseek(f, 0, SEEK_END);
1761+ long sz = ftell(f);
1762+ fseek(f, 0, SEEK_SET);
1763+ char *buf = sp_str_alloc(sz);
1764+ size_t n = 0;
1765+ if (sz > 0) {
1766+ n = fread(buf, 1, sz, f);
1767+ }
1768+ buf[n] = 0;
1769+ fclose(f);
1770+ return buf;
1771+}
1772+
1773+static void sp_file_write(const char *path, const char *data) {
1774+ if (sp_file_directory(path)) {
1775+ sp_raise_cls("Errno::EISDIR", sp_sprintf("Is a directory @ rb_sysopen - %s", path));
1776+ }
1777+ FILE *f = fopen(path, "wb");
1778+ if (f) {
1779+ fwrite(data, 1, sp_str_byte_len(data), f);
1780+ fclose(f);
1781+ }
1782+}
17561783 static mrb_bool sp_file_exist(const char *path) { FILE *f = fopen(path, "r"); if (f) { fclose(f); return TRUE; } return FALSE; }
17571784 static void sp_file_delete(const char *path) { remove(path); }
17581785 static const char *sp_backtick(const char *cmd) { FILE *p = popen(cmd, "r"); if (!p) return sp_str_empty; char *buf = sp_str_alloc_raw(4096); size_t n = fread(buf, 1, 4095, p); buf[n] = 0; pclose(p); return buf; }
@@ -1775,6 +1802,9 @@
17751802 null-termination and stops at the first 0x00 byte — wrong for
17761803 binary data (e.g. .nes ROM files). */
17771804 static sp_IntArray *sp_file_binread_bytes(const char *path) {
1805+ if (sp_file_directory(path)) {
1806+ sp_raise_cls("Errno::EISDIR", sp_sprintf("Is a directory @ io_fread - %s", path));
1807+ }
17781808 FILE *f = fopen(path, "rb");
17791809 sp_IntArray *a = sp_IntArray_new();
17801810 if (!f) return a;