net: shell: ensure the shell `sh` is valid before call shell_printf
It is possible that the `sh` was not set before use.
This change adds a NULL check for `sh` in the following macros:
PR, PR_SHELL, PR_ERROR, PR_INFO, and PR_WARNING.
In case `sh` is NULL, the above macros will call `printk` instead.
Fixes #68793
Signed-off-by: Pisit Sawangvonganan <pisit@ndrsolution.com>
(cherry picked from commit 7b8a9e1818f75a2a61ea40537a9d4299eb3225a6)
diff --git a/subsys/net/lib/shell/net_shell_private.h b/subsys/net/lib/shell/net_shell_private.h
index 8b55660..076bfd6 100644
--- a/subsys/net/lib/shell/net_shell_private.h
+++ b/subsys/net/lib/shell/net_shell_private.h
@@ -8,20 +8,50 @@
#include <zephyr/shell/shell.h>
#include <zephyr/net/net_ip.h>
-#define PR(fmt, ...) \
- shell_fprintf(sh, SHELL_NORMAL, fmt, ##__VA_ARGS__)
+#define PR(fmt, ...) \
+ do { \
+ if (sh) { \
+ shell_fprintf(sh, SHELL_NORMAL, fmt, ##__VA_ARGS__); \
+ } else { \
+ printk(fmt, ##__VA_ARGS__); \
+ } \
+ } while (false)
-#define PR_SHELL(sh, fmt, ...) \
- shell_fprintf(sh, SHELL_NORMAL, fmt, ##__VA_ARGS__)
+#define PR_SHELL(sh, fmt, ...) \
+ do { \
+ if (sh) { \
+ shell_fprintf(sh, SHELL_NORMAL, fmt, ##__VA_ARGS__); \
+ } else { \
+ printk(fmt, ##__VA_ARGS__); \
+ } \
+ } while (false)
-#define PR_ERROR(fmt, ...) \
- shell_fprintf(sh, SHELL_ERROR, fmt, ##__VA_ARGS__)
+#define PR_ERROR(fmt, ...) \
+ do { \
+ if (sh) { \
+ shell_fprintf(sh, SHELL_ERROR, fmt, ##__VA_ARGS__); \
+ } else { \
+ printk(fmt, ##__VA_ARGS__); \
+ } \
+ } while (false)
-#define PR_INFO(fmt, ...) \
- shell_fprintf(sh, SHELL_INFO, fmt, ##__VA_ARGS__)
+#define PR_INFO(fmt, ...) \
+ do { \
+ if (sh) { \
+ shell_fprintf(sh, SHELL_INFO, fmt, ##__VA_ARGS__); \
+ } else { \
+ printk(fmt, ##__VA_ARGS__); \
+ } \
+ } while (false)
-#define PR_WARNING(fmt, ...) \
- shell_fprintf(sh, SHELL_WARNING, fmt, ##__VA_ARGS__)
+#define PR_WARNING(fmt, ...) \
+ do { \
+ if (sh) { \
+ shell_fprintf(sh, SHELL_WARNING, fmt, ##__VA_ARGS__); \
+ } else { \
+ printk(fmt, ##__VA_ARGS__); \
+ } \
+ } while (false)
#include "net_private.h"
#include "../ip/ipv6.h"