[PATCH v2 3/7] selftests: kselftest: Add memfd_create syscall compatibility

Aqib Faruqui posted 7 patches 1 month ago
[PATCH v2 3/7] selftests: kselftest: Add memfd_create syscall compatibility
Posted by Aqib Faruqui 1 month ago
The memfd_create function and related MFD_* flags may not be available
in non-glibc C libraries. Some selftests use memfd_create for
memory backing operations.

Add fallback definitions for MFD_CLOEXEC and MFD_HUGETLB flags, and
provide a memfd_create wrapper.

Signed-off-by: Aqib Faruqui <aqibaf@amazon.com>
---
 tools/testing/selftests/kselftest.h        | 19 +++++++++++++++++++
 tools/testing/selftests/kvm/lib/kvm_util.c |  1 +
 2 files changed, 20 insertions(+)

diff --git a/tools/testing/selftests/kselftest.h b/tools/testing/selftests/kselftest.h
index c3b6d2604..f362c6766 100644
--- a/tools/testing/selftests/kselftest.h
+++ b/tools/testing/selftests/kselftest.h
@@ -57,6 +57,7 @@
 #include <string.h>
 #include <stdio.h>
 #include <sys/utsname.h>
+#include <sys/syscall.h>
 #endif
 
 #ifndef ARRAY_SIZE
@@ -80,6 +81,24 @@
 #endif
 #endif /* end arch */
 
+#ifndef MFD_CLOEXEC
+#define MFD_CLOEXEC 0x0001U
+#endif
+
+#ifndef MFD_HUGETLB
+#define MFD_HUGETLB 0x0004U
+#endif
+
+static inline int memfd_create(const char *name, unsigned int flags)
+{
+#ifdef __NR_memfd_create
+	return syscall(__NR_memfd_create, name, flags);
+#else
+	errno = ENOSYS;
+	return -1;
+#endif
+}
+
 /* define kselftest exit codes */
 #define KSFT_PASS  0
 #define KSFT_FAIL  1
diff --git a/tools/testing/selftests/kvm/lib/kvm_util.c b/tools/testing/selftests/kvm/lib/kvm_util.c
index c3f5142b0..a78b64117 100644
--- a/tools/testing/selftests/kvm/lib/kvm_util.c
+++ b/tools/testing/selftests/kvm/lib/kvm_util.c
@@ -15,6 +15,7 @@
 #include <sys/resource.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <sys/syscall.h>
 #include <unistd.h>
 #include <linux/kernel.h>
 
-- 
2.47.3