Skip to content

Commit a784a3a

Browse files
Chunyu-Huakpm00
authored andcommitted
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 <chuhu@redhat.com> Acked-by: David Hildenbrand (Arm) <david@kernel.org> Reviewed-by: Lorenzo Stoakes <ljs@kernel.org> Cc: Nico Pache <npache@redhat.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
1 parent 710d2f3 commit a784a3a

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

tools/testing/selftests/mm/vm_util.c

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -767,15 +767,24 @@ int unpoison_memory(unsigned long pfn)
767767

768768
void write_file(const char *path, const char *buf, size_t buflen)
769769
{
770-
int fd;
770+
int fd, saved_errno;
771771
ssize_t numwritten;
772772

773+
if (buflen < 2)
774+
ksft_exit_fail_msg("Incorrect buffer len: %zu\n", buflen);
775+
773776
fd = open(path, O_WRONLY);
774777
if (fd == -1)
775778
ksft_exit_fail_msg("%s open failed: %s\n", path, strerror(errno));
776779

777780
numwritten = write(fd, buf, buflen - 1);
781+
saved_errno = errno;
778782
close(fd);
779-
if (numwritten < 1)
780-
ksft_exit_fail_msg("Write failed\n");
783+
errno = saved_errno;
784+
if (numwritten < 0)
785+
ksft_exit_fail_msg("%s write(%.*s) failed: %s\n", path, (int)(buflen - 1),
786+
buf, strerror(errno));
787+
if (numwritten != buflen - 1)
788+
ksft_exit_fail_msg("%s write(%.*s) is truncated, expected %zu bytes, got %zd bytes\n",
789+
path, (int)(buflen - 1), buf, buflen - 1, numwritten);
781790
}

0 commit comments

Comments
 (0)