[PATCH v2 2/2] vsprintf: Add test for restricted kernel pointers
From: Thomas Weißschuh
Date: Mon May 04 2026 - 06:44:16 EST
Fill out the tests for restricted kernel pointers, using the %pK format.
Signed-off-by: Thomas Weißschuh <thomas.weissschuh@xxxxxxxxxxxxx>
---
Please note that changes to the kptr_restrict sysctl from the kernel
commandline are only applied *after* the boot-time KUnit tests run.
---
lib/tests/printf_kunit.c | 22 +++++++++++++++++++++-
lib/vsprintf.c | 3 +++
2 files changed, 24 insertions(+), 1 deletion(-)
diff --git a/lib/tests/printf_kunit.c b/lib/tests/printf_kunit.c
index bb70b9cddadd..58e639b01e83 100644
--- a/lib/tests/printf_kunit.c
+++ b/lib/tests/printf_kunit.c
@@ -319,7 +319,27 @@ symbol_ptr(struct kunit *kunittest)
static void
kernel_ptr(struct kunit *kunittest)
{
- /* We can't test this without access to kptr_restrict. */
+ switch (kptr_restrict) {
+ case 0:
+ if (no_hash_pointers) {
+ test(PTR_STR, "%pK", PTR);
+ } else {
+ char buf[PLAIN_BUF_SIZE];
+
+ plain_hash_to_buffer(kunittest, PTR, buf, PLAIN_BUF_SIZE);
+ /* %pK behaves the same as hashing */
+ test(buf, "%pK", PTR);
+ }
+ break;
+ case 1:
+ /* The KUnit kthread has all capabilities, including CAP_SYSLOG */
+ test(PTR_STR, "%pK", PTR);
+ break;
+ case 2:
+ default:
+ test(ZEROS "00000000", "%pK", PTR);
+ break;
+ }
}
static void
diff --git a/lib/vsprintf.c b/lib/vsprintf.c
index f70d240a394c..dc7e012a6ed7 100644
--- a/lib/vsprintf.c
+++ b/lib/vsprintf.c
@@ -859,6 +859,9 @@ static char *default_pointer(char *buf, char *end, const void *ptr,
}
int kptr_restrict __read_mostly;
+#if IS_MODULE(CONFIG_PRINTF_KUNIT_TEST)
+EXPORT_SYMBOL_FOR_MODULES(kptr_restrict, "printf_kunit");
+#endif
static noinline_for_stack
char *restricted_pointer(char *buf, char *end, const void *ptr,
--
2.53.0