Skip to contentSkip to conversation

selftests/x86/xstate: more test cases for coredump and ptrace

PATCH In review Chang S. Bae 1 participant 8 messages Nov 10 – Nov 20

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

cover selftests/x86/xstate: more test cases for coredump and ptrace

The recent PKRU bugfix [*] has motivated to address the missing test coverage for the case.

Since other XSTATE tests do not cover the coredump path either, ad x86 tests with shareable helpers and then include the PKRU test by reusing them.

While doing so, I also found a few missing ptrace cases and the gap of inefficient error tracking to those common tests. So the series ended up growing to address those things.

Thanks,
Chang

[*] https://lore.kernel.org/lkml/[email protected]

Chang S. Bae (6):
selftests/x86/xstate: Track testing status by kselftest API selftests/x86/xstate: Pre-allocate ptracee XSAVE buffer selftests/x86/xstate: Validate XSTATE_BV in ptrace test selftests/x86/xstate: Validate state reset in ptrace test selftests/x86/xstate: Add coredump test selftests/mm: Add coredump test for x86

 tools/testing/selftests/mm/Makefile           |   2 +-
 tools/testing/selftests/mm/pkey-x86.h         |   1 +
 .../selftests/mm/pkey_coredump_tests.c        |  89 +++++++
 tools/testing/selftests/mm/run_vmtests.sh     |  11 +
 tools/testing/selftests/x86/amx.c             |   5 +-
 tools/testing/selftests/x86/apx.c             |   2 +-
 tools/testing/selftests/x86/avx.c             |  33 ++-
 tools/testing/selftests/x86/coredump.h        | 229 ++++++++++++++++
 tools/testing/selftests/x86/xstate.c          | 246 ++++++++++++++----
 tools/testing/selftests/x86/xstate.h          |   2 +-
 10 files changed, 561 insertions(+), 59 deletions(-)
 create mode 100644 tools/testing/selftests/mm/pkey_coredump_tests.c
 create mode 100644 tools/testing/selftests/x86/coredump.h

base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb

Signature · 1 line
2.53.0
#1 lore raw

PATCH 1/6 selftests/x86/xstate: Track testing status by kselftest API

The XSTATE facility is shared across different component testing. Currently, it relies on plain printf() for reporting results, which provides less convenient way to track failures or determine the overall test status.

Convert the test code to use the kselftest framework for result tracking and and a return value in the end.

While at it, also shorten and refine the test messages a bit.

---
 tools/testing/selftests/x86/amx.c    |   5 +-
 tools/testing/selftests/x86/apx.c    |   2 +-
 tools/testing/selftests/x86/avx.c    |  33 +++++-
 tools/testing/selftests/x86/xstate.c | 155 +++++++++++++++++++--------
 tools/testing/selftests/x86/xstate.h |   2 +-
 5 files changed, 142 insertions(+), 55 deletions(-)
tools/testing/selftests/x86/amx.c +3 -2
index 40769c16de1b..1e4206c8a03a 100644
@@ -482,6 +482,7 @@ int main(void)
 {
 	unsigned long features;
 	long rc;
+	int ret;
 
 	rc = syscall(SYS_arch_prctl, ARCH_GET_XCOMP_SUPP, &features);
 	if (rc || (features & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE) {
@@ -509,10 +510,10 @@ int main(void)
 	 * Perform generic xstate tests for context switching, ptrace,
 	 * and signal.
 	 */
-	test_xstate(XFEATURE_XTILEDATA);
+	ret = test_xstate(XFEATURE_XTILEDATA);
 
 	clearhandler(SIGILL);
 	free_stashed_xsave();
 
-	return 0;
+	return ret;
 }
tools/testing/selftests/x86/apx.c +1 -1
index d9c8d41b8c5a..8d353b75bca1 100644
@@ -6,5 +6,5 @@
 
 int main(void)
 {
-	test_xstate(XFEATURE_APX);
+	return test_xstate(XFEATURE_APX);
 }
tools/testing/selftests/x86/avx.c +29 -4
index 11d5367c235f..2b79da16ee2b 100644
@@ -3,10 +3,35 @@
 #define _GNU_SOURCE /* Required for inline xstate helpers */
 #include "xstate.h"
 
+static uint32_t avx_features[] = {
+	XFEATURE_YMM,
+	XFEATURE_OPMASK,
+	XFEATURE_ZMM_Hi256,
+	XFEATURE_Hi16_ZMM,
+};
+
 int main(void)
 {
-	test_xstate(XFEATURE_YMM);
-	test_xstate(XFEATURE_OPMASK);
-	test_xstate(XFEATURE_ZMM_Hi256);
-	test_xstate(XFEATURE_Hi16_ZMM);
+	unsigned int failed = 0, skipped = 0;
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(avx_features); i++) {
+		switch (test_xstate(avx_features[i])) {
+		case KSFT_FAIL:
+			failed++;
+			break;
+		case KSFT_SKIP:
+			skipped++;
+			break;
+		case KSFT_PASS:
+		default:
+		}
+	}
+
+	if (skipped == ARRAY_SIZE(avx_features))
+		return KSFT_SKIP;
+	else if (failed)
+		return KSFT_FAIL;
+	else
+		return KSFT_PASS;
 }
tools/testing/selftests/x86/xstate.c +108 -47

270 lines not on this page · raw message

tools/testing/selftests/x86/xstate.h +1 -1
index eedf0cab7ccb..5e712c979dc1 100644
@@ -212,6 +212,6 @@ static inline void set_rand_data(struct xstate_info *xstate, struct xsave_buffer
 }
 
 /* Testing kernel's context switching and ABI support for the xstate. */
-void test_xstate(uint32_t feature_num);
+int test_xstate(uint32_t feature_num);
 
 #endif /* __SELFTESTS_X86_XSTATE_H */
Signature · 1 line
2.53.0
#2 lore raw

PATCH 2/6 selftests/x86/xstate: Pre-allocate ptracee XSAVE buffer

In reply to Chang S. Bae

Currently, the ptrace test does not handle XSAVE buffer allocation failures in the child process. But such a failure can lead to an unexpected exit path, complicating error handling.

Instead, allocate the buffer in the parent process so that allocation and error handling are handled before forking the child.

---
 tools/testing/selftests/x86/xstate.c | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)
tools/testing/selftests/x86/xstate.c +10 -10
index c26dbe33622f..240567e79e96 100644
@@ -236,6 +236,8 @@ static void test_context_switch(void)
 	free(finfo);
 }
 
+static struct xsave_buffer *stashed_xbuf;
+
 /*
  * Ptrace test for the ABI format as described in arch/x86/include/asm/user.h
  */
@@ -247,14 +249,8 @@ static void test_context_switch(void)
  */
 static inline void ptracee_touch_xstate(void)
 {
-	struct xsave_buffer *xbuf;
-
-	xbuf = alloc_xbuf();
-
-	load_rand_xstate(&xstate, xbuf);
-	load_init_xstate(&xstate, xbuf);
-
-	free(xbuf);
+	load_rand_xstate(&xstate, stashed_xbuf);
+	load_init_xstate(&xstate, stashed_xbuf);
 }
 
 static bool validate_ptracer_xstate(pid_t target, struct iovec iov,
@@ -335,6 +331,10 @@ static void test_ptrace(void)
 	pid_t child;
 	int status;
 
+	stashed_xbuf = alloc_xbuf();
+	if (!stashed_xbuf)
+		ksft_exit_fail_msg("unable to allocate XSAVE buffer\n");
+
 	child = fork();
 	if (child < 0) {
 		ksft_exit_fail_msg("fork() failed\n");
@@ -358,6 +358,8 @@ static void test_ptrace(void)
 	wait(&status);
 	if (!WIFEXITED(status) || WEXITSTATUS(status))
 		ksft_exit_fail_msg("ptracee exit error\n");
+
+	free(stashed_xbuf);
 }
 
 /*
@@ -391,8 +393,6 @@ static inline void sig_print_fail(char *msg)
 	sig_print(msg);
 }
 
-static struct xsave_buffer *stashed_xbuf;
-
 static void validate_sigfpstate(int sig, siginfo_t *si, void *ctx_void)
 {
 	ucontext_t *ctx = (ucontext_t *)ctx_void;
Signature · 1 line
2.53.0
#3 lore raw

PATCH 3/6 selftests/x86/xstate: Validate XSTATE_BV in ptrace test

In reply to Chang S. Bae

The ptrace test does not currently validate XSTATE_BV in the XSAVE header. Add a check for it.

The component bit may legitimately be clear when testing a reset state. So, ensure the expected bit setting first and then compare the component bit directly.

---
 tools/testing/selftests/x86/xstate.c | 8 ++++++++
 1 file changed, 8 insertions(+)
tools/testing/selftests/x86/xstate.c +8 -0
index 240567e79e96..93ba4b5f1a08 100644
@@ -62,6 +62,7 @@ static inline void load_init_xstate(struct xstate_info *xstate, struct xsave_buf
 
 static inline void copy_xstate(struct xsave_buffer *xbuf_dst, struct xsave_buffer *xbuf_src)
 {
+	memcpy(xbuf_dst->header, xbuf_src->header, XSAVE_HDR_SIZE);
 	memcpy(&xbuf_dst->bytes[xstate.xbuf_offset],
 	       &xbuf_src->bytes[xstate.xbuf_offset],
 	       xstate.size);
@@ -277,6 +278,13 @@ static bool validate_ptracer_xstate(pid_t target, struct iovec iov,
 		failed++;
 	}
 
+	if ((xstate.mask & get_xstatebv(xbuf)) == (xstate.mask & get_xstatebv(expected))) {
+		printf("#\tok\tXSTATE_BV\n");
+	} else {
+		printf("#\tnot ok\tXSTATE_BV\n");
+		failed++;
+	}
+
 	if (validate_xstate_same(xbuf, expected)) {
 		printf("#\tok\txstate area\n");
 	} else {
Signature · 1 line
2.53.0
#4 lore raw

Re: [PATCH 3/6] selftests/x86/xstate: Validate XSTATE_BV in ptrace test

tools/testing/selftests/x86/xstate.c static bool validate_ptracer_xstate(pid_t target, struct iovec iov, · line 286

Quoted 7 lines · Chang S. Bae
tools/testing/selftests/x86/xstate.c +6 -0
+	if ((xstate.mask & get_xstatebv(xbuf)) == (xstate.mask & get_xstatebv(expected))) {
+		printf("#\tok\tXSTATE_BV\n");
+	} else {
+		printf("#\tnot ok\tXSTATE_BV\n");
+		failed++;
+	}

This check looks excessive because of the XSAVE behavior.

If the kernel ever falls back to XSAVE instead of its variants like XSAVES, XSTATE_BV may be set even if a component stays in init-state. Whether the bit is cleared or not depends on the init-tracking implementation.

So, the most this check can do is ensuring XSTATE_BV is set when the state actually carries non-init values. Let me fix on my next posting.

Thanks,
Chang

#5 lore raw

PATCH 4/6 selftests/x86/xstate: Validate state reset in ptrace test

In reply to Chang S. Bae

Clearing a feature bit in XSTATE_BV should cause the state component to be initialized when the ptracer retrieves the state. Validate this behavior.

---
I missed this before. During a review on my other thing, I realized and now adding... Thanks, Jim Mattson!

---
 tools/testing/selftests/x86/xstate.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
tools/testing/selftests/x86/xstate.c +19 -1
index 93ba4b5f1a08..a2f25ca848fb 100644
@@ -330,6 +330,24 @@ static void ptracer_inject_xstate(pid_t target)
 	else
 		ksft_test_result_fail("%s for %s\n", __func__, xstate.name);
 
+	ksft_print_msg("[RUN]\t%s: reset xstate via ptrace().\n", xstate.name);
+
+	/* Reset the feature bit in XSTATE_BV only, expecting init-state back */
+	set_xstatebv(xbuf1, get_xstatebv(xbuf1) & ~xstate.mask);
+
+	/*
+	 * Prepare reference data. Note not every XSAVE implementation resets
+	 * the XSTATE_BV bit even though the component is in init-state.
+	 */
+	load_init_xstate(&xstate, xbuf2);
+	xsave(xbuf2, xstate.mask);
+	set_xstatebv(xbuf2, get_xstatebv(xbuf2) & ~xstate.mask);
+
+	if (validate_ptracer_xstate(target, iov, xbuf1, xbuf2))
+		ksft_test_result_pass("%s (reset) for %s\n", __func__, xstate.name);
+	else
+		ksft_test_result_fail("%s (reset) for %s\n", __func__, xstate.name);
+
 	free(xbuf1);
 	free(xbuf2);
 }
@@ -491,7 +509,7 @@ static struct test_info {
 	unsigned int nr;
 } tests[] = {
 	{ .nr = 1, .fn = test_context_switch, },
-	{ .nr = 1, .fn = test_ptrace, },
+	{ .nr = 2, .fn = test_ptrace, },
 	{ .nr = 2, .fn = test_signal, },
 };
 
Signature · 1 line
2.53.0
#6 lore raw

PATCH 5/6 selftests/x86/xstate: Add coredump test

In reply to Chang S. Bae

The existing ptrace test exercises much of the XSTATE ABI handling, but it does not cover the coredump path entirely. Add a dedicated test to validate XSTATE handling in core dumps.

Refactor the XSAVE buffer validation code from the ptrace test for reuse. Also, move most of the coredump-specific preparation and handling into a header so that the PKRU test outside the x86 selftest can reuse it.

---
 tools/testing/selftests/x86/coredump.h | 229 +++++++++++++++++++++++++
 tools/testing/selftests/x86/xstate.c   |  99 ++++++++---
 2 files changed, 308 insertions(+), 20 deletions(-)
 create mode 100644 tools/testing/selftests/x86/coredump.h
tools/testing/selftests/x86/coredump.h new file +229 -0
new file mode 100644
index 000000000000..8aef96667f87
@@ -0,0 +1,229 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#ifndef __SELFTESTS_X86_COREDUMP_H
+#define __SELFTESTS_X86_COREDUMP_H
+
+#include <link.h>
+#include <stdint.h>
+#include <fcntl.h>
+#include <limits.h>
+
+#include <sys/resource.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+
+#include "kselftest.h"
+
+#define CORE_PATTERN_PATH "/proc/sys/kernel/core_pattern"
+#ifndef CORENAME_MAX_SIZE
+#define CORENAME_MAX_SIZE 128
+#endif
+
+static char orig_pattern[CORENAME_MAX_SIZE];
+
+static inline bool get_core_pattern(char *buf, int size)
+{
+	bool ret;
+	FILE *fp;
+
+	if (!buf)
+		return false;
+
+	fp = fopen(CORE_PATTERN_PATH, "r");
+	if (!fp)
+		return false;
+
+	ret = fgets(buf, size, fp) != NULL;
+	if (ret)
+		buf[strcspn(buf, "\n")] = 0;
+
+	fclose(fp);
+
+	return ret;
+}
+
+static inline bool set_core_pattern(const char *pattern)
+{
+	bool ret;
+	FILE *fp;
+
+	if (!pattern)
+		return false;
+
+	fp = fopen(CORE_PATTERN_PATH, "w");
+	if (!fp)
+		return false;
+
+	ret = fprintf(fp, "%s\n", pattern) >= 0;
+
+	fclose(fp);
+
+	return ret;
+}
+
+static inline bool save_core_pattern(void)
+{
+	return get_core_pattern(orig_pattern, CORENAME_MAX_SIZE);
+}
+
+static inline bool set_test_core_pattern(void)
+{
+	const char test_pattern[] = "core.%p";
+
+	if (!strcmp(orig_pattern, test_pattern))
+		return true;
+
+	return set_core_pattern(test_pattern);
+}
+
+static inline bool restore_core_pattern(void)
+{
+	return set_core_pattern(orig_pattern);
+}
+
+static char core_dir[] = "/tmp/x86-coredump-XXXXXX";
+
+static struct corefile {
+	bool dumped;
+	int fd;
+	struct stat st;
+	char *image;
+	char path[PATH_MAX];
+} core_file = { false, -1, { }, NULL, "\0" };
+
+static inline void corefile_reset(void)
+{
+	close(core_file.fd);
+	unlink(core_file.path);
+
+	if (core_file.image != NULL && core_file.image != MAP_FAILED)
+		munmap((void *)core_file.image, core_file.st.st_size);
+
+	core_file = (struct corefile){ .dumped = false, .fd = -1, .st = { },
+				       .image = NULL, .path = "\0" };
+}
+
+static inline void coredump_cleanup(void)
+{
+	if (core_file.dumped)
+		corefile_reset();
+
+	rmdir(core_dir);
+	strcpy(core_dir, "/tmp/x86-coredump-XXXXXX");
+	restore_core_pattern();
+}
+
+/*
+ * Create a temporary directory for the core file and configure core_pattern to
+ * use a predictable file name. Save the original pattern so it can be restored
+ * after the test.
+ */
+static inline bool coredump_prepare(void)
+{
+	struct rlimit lim = { RLIM_INFINITY, RLIM_INFINITY };
+
+	if (setrlimit(RLIMIT_CORE, &lim)) {
+		ksft_test_result_skip("Failed to set rlimit. core Try sudo.\n");
+		return false;
+	}
+
+	if (!save_core_pattern()) {
+		ksft_test_result_skip("Failed to save core pattern.\n");
+		return false;
+	}
+
+	if (!set_test_core_pattern()) {
+		ksft_test_result_skip("Failed to update core pattern. Try sudo.\n");
+		return false;
+	}
+
+	if (!mkdtemp(core_dir)) {
+		coredump_cleanup();
+		ksft_test_result_skip("Failed to create test folder.\n");
+		return false;
+	}
+
+	return true;
+}
+
+/* Always call this for any failed exit after coredump_prepare() */
+static inline void coredump_exit_fail_msg(const char *msg)
+{
+	coredump_cleanup();
+	ksft_exit_fail_msg("%s\n", msg);
+}
+
+static inline void coredump_trigger(void)
+{
+	volatile unsigned int *ptr = NULL;
+
+	*ptr = 0xDEAD;
+}
+
+static inline void corefile_map(pid_t child)
+{
+	snprintf(core_file.path, sizeof(core_file.path), "%s/core.%d", core_dir, child);
+
+	core_file.fd = open(core_file.path, O_RDONLY);
+	if (core_file.fd < 0)
+		coredump_exit_fail_msg("Cannot open core file.");
+
+	core_file.dumped = true;
+
+	if (fstat(core_file.fd, &core_file.st))
+		coredump_exit_fail_msg("Invalid core file.");
+
+	core_file.image = mmap(NULL, core_file.st.st_size, PROT_READ, MAP_PRIVATE, core_file.fd, 0);
+	if (core_file.image == MAP_FAILED)
+		coredump_exit_fail_msg("Cannot map core file.");
+}
+
+#ifndef NT_X86_XSTATE
+#define NT_X86_XSTATE	0x202
+#endif
+
+#define next_pos(pos, size)		((pos) + (((size) + 3) & ~3))
+
+/* Program Header */
+#define phdr_ptr(core, offset)		(ElfW(Phdr) *)(core + offset)
+
+/* Note Header */
+#define nhdr_ptr(core, offset)		(ElfW(Nhdr) *)(core + offset)
+
+/*
+ * Locate the NT_X86_XSTATE note in the ELF core image and return a pointer to
+ * its XSTATE data.
+ */
+static inline char *retrieve_corefile_xbuf(void)
+{
+	ElfW(Ehdr) *ehdr;
+	ElfW(Phdr) *phdr;
+	ElfW(Nhdr) *nhdr;
+	size_t pos, end;
+	int i;
+
+	ehdr = (ElfW(Ehdr) *)core_file.image;
+	phdr = phdr_ptr(core_file.image, ehdr->e_phoff);
+
+	for (i = 0; i < ehdr->e_phnum; i++) {
+		if (phdr[i].p_type != PT_NOTE)
+			continue;
+
+		end = phdr[i].p_offset + phdr[i].p_filesz;
+		pos = phdr[i].p_offset;
+
+		while (pos + sizeof(*nhdr) <= end) {
+			nhdr  = nhdr_ptr(core_file.image, pos);
+			pos   = next_pos(pos + sizeof(*nhdr), nhdr->n_namesz);
+
+			if (nhdr->n_type == NT_X86_XSTATE)
+				return core_file.image + pos;
+
+			pos = next_pos(pos, nhdr->n_descsz);
+		}
+	}
+
+	coredump_exit_fail_msg("No NT_X86_XSTATE was found.");
+	_exit(1);
+}
+
+#endif /* __SELFTESTS_X86_COREDUMP_H */
tools/testing/selftests/x86/xstate.c +79 -20

132 lines not on this page · raw message

Signature · 1 line
2.53.0
#7 lore raw

PATCH 6/6 selftests/mm: Add coredump test for x86

In reply to Chang S. Bae

There is currently no test covering the coredump path for PKRU. Add one by reusing the helpers from the x86 selftests.

---
Note: The test fails right now. So the fix [*] should get in first.

[*] https://lore.kernel.org/lkml/[email protected]/

---
 tools/testing/selftests/mm/Makefile           |  2 +-
 tools/testing/selftests/mm/pkey-x86.h         |  1 +
 .../selftests/mm/pkey_coredump_tests.c        | 89 +++++++++++++++++++
 tools/testing/selftests/mm/run_vmtests.sh     | 11 +++
 4 files changed, 102 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/mm/pkey_coredump_tests.c
tools/testing/selftests/mm/Makefile +1 -1
index 0ea72e997934..d687936c8144 100644
@@ -116,7 +116,7 @@ CAN_BUILD_X86_64 := $(shell ./../x86/check_cc.sh "$(CC)" ../x86/trivial_64bit_pr
 CAN_BUILD_WITH_NOPIE := $(shell ./../x86/check_cc.sh "$(CC)" ../x86/trivial_program.c -no-pie)
 
 VMTARGETS := protection_keys
-VMTARGETS += pkey_sighandler_tests
+VMTARGETS += pkey_sighandler_tests pkey_coredump_tests
 BINARIES_32 := $(VMTARGETS:%=%_32)
 BINARIES_64 := $(VMTARGETS:%=%_64)
 
tools/testing/selftests/mm/pkey-x86.h +1 -0
index f7ecd335df1e..5b16e9ebcb2d 100644
@@ -112,6 +112,7 @@ static inline u32 pkey_bit_position(int pkey)
 #define XSTATE_PKEY_BIT	(9)
 #define XSTATE_PKEY	0x200
 #define XSTATE_BV_OFFSET	512
+#define XSTATE_SW_BYTES_OFFSET	464
 
 static inline int pkey_reg_xstate_offset(void)
 {
tools/testing/selftests/mm/pkey_coredump_tests.c new file +89 -0

89 lines not on this page · raw message

tools/testing/selftests/mm/run_vmtests.sh +11 -0
index a1b45a3dedae..bf7c8aa0b098 100755
@@ -373,6 +373,17 @@ then
 	CATEGORY="pkey" run_test ./protection_keys_64
 fi
 
+# pkey_coredump tests
+if [ -x ./pkey_coredump_tests_32 ]
+then
+	CATEGORY="pkey" run_test ./pkey_coredump_tests_32
+fi
+
+if [ -x ./pkey_coredump_tests_64 ]
+then
+	CATEGORY="pkey" run_test ./pkey_coredump_tests_64
+fi
+
 CATEGORY="soft_dirty" run_test ./soft-dirty
 
 CATEGORY="pagemap" run_test ./pagemap_ioctl
Signature · 1 line
2.53.0