[RFC PATCH v2 2/6] KVM: selftests: Add negative test cases for punch hole for guest_memfd()

isaku.yamahata
2023-09-21T20:41:18Z

From: Isaku Yamahata <isaku.yamahata@intel.com>

Add test cases to check for punch hole of guest_memfd to reject unaligned
offset or size.

Signed-off-by: Isaku Yamahata <isaku.yamahata@intel.com>
---
.../testing/selftests/kvm/guest_memfd_test.c | 32 +++++++++++++++++++
1 file changed, 32 insertions(+)

diff --git a/tools/testing/selftests/kvm/guest_memfd_test.c b/tools/testing/selftests/kvm/guest_memfd_test.c
index 75073645aaa1..d5b4bfcdc3fe 100644
--- a/tools/testing/selftests/kvm/guest_memfd_test.c
+++ b/tools/testing/selftests/kvm/guest_memfd_test.c
@@ -91,6 +91,37 @@ static void test_fallocate(int fd, size_t page_size, size_t total_size)
TEST_ASSERT(!ret, "fallocate to restore punched hole should succeed");
}

+/* Negative tests */
+static void test_fallocate_fail(int fd, size_t page_size, size_t total_size)
+{
+ struct {
+ off_t offset;
+ off_t len;
+ } cases[] = {
+ {0, 1},
+ {0, page_size - 1},
+ {0, page_size + 1},
+
+ {1, 1},
+ {1, page_size - 1},
+ {1, page_size},
+ {1, page_size + 1},
+
+ {page_size, 1},
+ {page_size, page_size - 1},
+ {page_size, page_size + 1},
+ };
+ int ret;
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(cases); i++) {
+ ret = fallocate(fd, FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE,
+ cases[i].offset, cases[i].len);
+ TEST_ASSERT(ret == -1,
+ "fallocate(PUNCH_HOLE) with unaligned offset and/or size should fail");
+ }
+}
+
static void test_create_guest_memfd_invalid(struct kvm_vm *vm)
{
uint64_t valid_flags = 0;
@@ -160,6 +191,7 @@ int main(int argc, char *argv[])
test_mmap(fd, page_size);
test_file_size(fd, page_size, total_size);
test_fallocate(fd, page_size, total_size);
+ test_fallocate_fail(fd, page_size, total_size);

close(fd);
}
--
2.25.1