1 /*
2  * Copyright (c) 2018 Nordic Semiconductor ASA
3  * Copyright (c) 2018 Intel Corporation
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <stdio.h>
9 #include <stddef.h>
10 #include <zephyr/logging/log_backend.h>
11 #include <zephyr/logging/log_backend_std.h>
12 #include <zephyr/logging/log_core.h>
13 #include <zephyr/logging/log_output.h>
14 #include <zephyr/irq.h>
15 #include <zephyr/arch/posix/posix_trace.h>
16 
17 #define _STDOUT_BUF_SIZE 256
18 static char stdout_buff[_STDOUT_BUF_SIZE];
19 static int n_pend; /* Number of pending characters in buffer */
20 static uint32_t log_format_current = CONFIG_LOG_BACKEND_NATIVE_POSIX_OUTPUT_DEFAULT;
21 
preprint_char(int c)22 static void preprint_char(int c)
23 {
24 	int printnow = 0;
25 
26 	if (c == '\r') {
27 		/* Discard carriage returns */
28 		return;
29 	}
30 	if (c != '\n') {
31 		stdout_buff[n_pend++] = c;
32 		stdout_buff[n_pend] = 0;
33 	} else {
34 		printnow = 1;
35 	}
36 
37 	if (n_pend >= _STDOUT_BUF_SIZE - 1) {
38 		printnow = 1;
39 	}
40 
41 	if (printnow) {
42 		posix_print_trace("%s\n", stdout_buff);
43 		n_pend = 0;
44 		stdout_buff[0] = 0;
45 	}
46 }
47 
48 static uint8_t buf[_STDOUT_BUF_SIZE];
49 
char_out(uint8_t * data,size_t length,void * ctx)50 static int char_out(uint8_t *data, size_t length, void *ctx)
51 {
52 	for (size_t i = 0; i < length; i++) {
53 		preprint_char(data[i]);
54 	}
55 
56 	return length;
57 }
58 
59 LOG_OUTPUT_DEFINE(log_output_posix, char_out, buf, sizeof(buf));
60 
panic(struct log_backend const * const backend)61 static void panic(struct log_backend const *const backend)
62 {
63 	log_output_flush(&log_output_posix);
64 }
65 
dropped(const struct log_backend * const backend,uint32_t cnt)66 static void dropped(const struct log_backend *const backend, uint32_t cnt)
67 {
68 	ARG_UNUSED(backend);
69 
70 	log_output_dropped_process(&log_output_posix, cnt);
71 }
72 
process(const struct log_backend * const backend,union log_msg_generic * msg)73 static void process(const struct log_backend *const backend,
74 		union log_msg_generic *msg)
75 {
76 	uint32_t flags = log_backend_std_get_flags();
77 
78 	log_format_func_t log_output_func = log_format_func_t_get(log_format_current);
79 
80 	log_output_func(&log_output_posix, &msg->log, flags);
81 }
82 
format_set(const struct log_backend * const backend,uint32_t log_type)83 static int format_set(const struct log_backend *const backend, uint32_t log_type)
84 {
85 	log_format_current = log_type;
86 	return 0;
87 }
88 
89 const struct log_backend_api log_backend_native_posix_api = {
90 	.process = process,
91 	.panic = panic,
92 	.dropped = IS_ENABLED(CONFIG_LOG_MODE_IMMEDIATE) ? NULL : dropped,
93 	.format_set = format_set,
94 };
95 
96 LOG_BACKEND_DEFINE(log_backend_native_posix,
97 		   log_backend_native_posix_api,
98 		   true);
99