From: Chunyu Hu Date: Thu, 2 Apr 2026 01:45:41 +0000 (+0800) Subject: selftests/mm/vm_util: robust write_file() X-Git-Url: http://git.ipfire.org/index.cgi?a=commitdiff_plain;h=a784a3a39cc58b45807083b6447fa13028fd47e7;p=thirdparty%2Flinux.git selftests/mm/vm_util: robust write_file() Add three more checks for buflen and numwritten. The buflen should be at least two, that means at least one char and the null-end. The error case check is added by checking numwriten < 0 instead of numwritten < 1. And the truncate case is checked. The test will exit if any of these conditions aren't met. Additionally, add more print information when a write failure occurs or a truncated write happens, providing clearer diagnostics. Link: https://lore.kernel.org/20260402014543.1671131-5-chuhu@redhat.com Signed-off-by: Chunyu Hu Acked-by: David Hildenbrand (Arm) Reviewed-by: Lorenzo Stoakes Cc: Nico Pache Signed-off-by: Andrew Morton --- diff --git a/tools/testing/selftests/mm/vm_util.c b/tools/testing/selftests/mm/vm_util.c index ad96d19d1b85..db94564f4431 100644 --- a/tools/testing/selftests/mm/vm_util.c +++ b/tools/testing/selftests/mm/vm_util.c @@ -767,15 +767,24 @@ int unpoison_memory(unsigned long pfn) void write_file(const char *path, const char *buf, size_t buflen) { - int fd; + int fd, saved_errno; ssize_t numwritten; + if (buflen < 2) + ksft_exit_fail_msg("Incorrect buffer len: %zu\n", buflen); + fd = open(path, O_WRONLY); if (fd == -1) ksft_exit_fail_msg("%s open failed: %s\n", path, strerror(errno)); numwritten = write(fd, buf, buflen - 1); + saved_errno = errno; close(fd); - if (numwritten < 1) - ksft_exit_fail_msg("Write failed\n"); + errno = saved_errno; + if (numwritten < 0) + ksft_exit_fail_msg("%s write(%.*s) failed: %s\n", path, (int)(buflen - 1), + buf, strerror(errno)); + if (numwritten != buflen - 1) + ksft_exit_fail_msg("%s write(%.*s) is truncated, expected %zu bytes, got %zd bytes\n", + path, (int)(buflen - 1), buf, buflen - 1, numwritten); }