From 4ee7dd72d0d6d6c7be98902b11b21c4fb023a91e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=80=9A=E6=B4=B2?= Date: Tue, 28 Apr 2026 09:03:24 +0800 Subject: [PATCH] IO: improves code quality & reliablity --- src/common/impl/io_unix.c | 8 +++----- src/common/impl/io_windows.c | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/common/impl/io_unix.c b/src/common/impl/io_unix.c index 65cc9121a..a7e0b041d 100644 --- a/src/common/impl/io_unix.c +++ b/src/common/impl/io_unix.c @@ -252,14 +252,14 @@ bool ffSuppressIO(bool suppress) { } void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indentation, const char* folderName, bool pretty) { - FF_AUTO_CLOSE_FD int dfd = open(folder->chars, O_RDONLY | O_CLOEXEC); + int dfd = open(folder->chars, O_RDONLY | O_CLOEXEC | O_DIRECTORY); // Ownership of dfd will be transformed to dir if (dfd < 0) { return; } - DIR* dir = fdopendir(dfd); + FF_AUTO_CLOSE_DIR DIR* dir = fdopendir(dfd); if (dir == NULL) { - return; + return; // Should not happen } uint32_t folderLength = folder->length; @@ -310,8 +310,6 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta puts(entry->d_name); } - - closedir(dir); } void ffListFilesRecursively(const char* path, bool pretty) { diff --git a/src/common/impl/io_windows.c b/src/common/impl/io_windows.c index 49b49df09..6e720396e 100644 --- a/src/common/impl/io_windows.c +++ b/src/common/impl/io_windows.c @@ -387,10 +387,12 @@ void ffListFilesRecursively(const char* path, bool pretty) { const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...) { HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); FF_AUTO_CLOSE_FD HANDLE hConin = INVALID_HANDLE_VALUE; - DWORD inputMode; - if (!GetConsoleMode(hInput, &inputMode)) { + DWORD inputMode = 0; + bool hasInputMode = !!GetConsoleMode(hInput, &inputMode); + if (!hasInputMode) { hConin = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, NULL); hInput = hConin; + hasInputMode = !!GetConsoleMode(hInput, &inputMode); } SetConsoleMode(hInput, 0); @@ -439,12 +441,16 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* while (true) { DWORD bytes = 0; - if (!ReadFile(hInput, buffer, sizeof(buffer) - 1, &bytes, NULL) || bytes == 0) { + if (!ReadFile(hInput, buffer + bytesRead, (DWORD)(sizeof(buffer) - 1 - bytesRead), &bytes, NULL) || bytes == 0) { va_end(args); return "ReadFile() failed"; } bytesRead += bytes; + if (__builtin_expect(bytesRead >= sizeof(buffer) - 1, false)) { + va_end(args); + return "terminal response buffer overflow"; + } buffer[bytesRead] = '\0'; va_list cargs; @@ -461,7 +467,9 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* } } - SetConsoleMode(hInput, inputMode); + if (hasInputMode) { + SetConsoleMode(hInput, inputMode); + } va_end(args);