1 /*
2  * Copyright (c) 2018 Oticon A/S
3  * Copyright (c) 2023 Nordic Semiconductor ASA
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/init.h>
9 #include <zephyr/arch/posix/posix_trace.h>
10 #include <zephyr/sys/printk-hooks.h>
11 #include <zephyr/sys/libc-hooks.h>
12 
13 #define _STDOUT_BUF_SIZE 256
14 static char stdout_buff[_STDOUT_BUF_SIZE];
15 static int n_pend; /* Number of pending characters in buffer */
16 
17 #if defined(CONFIG_PRINTK) || defined(CONFIG_STDOUT_CONSOLE)
print_char(int c)18 static int print_char(int c)
19 {
20 	int printnow = 0;
21 
22 	if ((c != '\n') && (c != '\r')) {
23 		stdout_buff[n_pend++] = c;
24 		stdout_buff[n_pend] = 0;
25 	} else {
26 		printnow = 1;
27 	}
28 
29 	if (n_pend >= _STDOUT_BUF_SIZE - 1) {
30 		printnow = 1;
31 	}
32 
33 	if (printnow) {
34 		posix_print_trace("%s\n", stdout_buff);
35 		n_pend = 0;
36 		stdout_buff[0] = 0;
37 	}
38 	return c;
39 }
40 #endif /* defined(CONFIG_PRINTK) || defined(CONFIG_STDOUT_CONSOLE) */
41 
42 /**
43  * Ensure that whatever was written thru printk is displayed now
44  */
posix_flush_stdout(void)45 void posix_flush_stdout(void)
46 {
47 	if (n_pend) {
48 		stdout_buff[n_pend] = 0;
49 		posix_print_trace("%s", stdout_buff);
50 		n_pend = 0;
51 		stdout_buff[0] = 0;
52 	}
53 }
54 
posix_arch_console_init(void)55 static int posix_arch_console_init(void)
56 {
57 #ifdef CONFIG_PRINTK
58 	__printk_hook_install(print_char);
59 #endif
60 #ifdef CONFIG_STDOUT_CONSOLE
61 	__stdout_hook_install(print_char);
62 #endif
63 	return 0;
64 }
65 
66 SYS_INIT(posix_arch_console_init, PRE_KERNEL_1,
67 	CONFIG_POSIX_ARCH_CONSOLE_INIT_PRIORITY);
68