1 /* Copyright (c) 2024 Contributors to the logging subsystem.
2  * SPDX-License-Identifier: Apache-2.0
3  */
4 #include <stdio.h>
5 #include <stddef.h>
6 #include <zephyr/logging/log_backend.h>
7 #include <zephyr/logging/log_backend_std.h>
8 #include <zephyr/logging/log_core.h>
9 #include <zephyr/logging/log_output.h>
10 #include <zephyr/arch/common/semihost.h>
11 
12 static uint8_t buf[CONFIG_LOG_BACKEND_SEMIHOST_BUFFER_SIZE];
13 static uint32_t log_format_current = CONFIG_LOG_BACKEND_SEMIHOST_OUTPUT_DEFAULT;
14 
char_out(uint8_t * data,size_t length,void * ctx)15 static int char_out(uint8_t *data, size_t length, void *ctx)
16 {
17 	ARG_UNUSED(ctx);
18 #define SEMIHOST_STDOUT (1)
19 	int ret = semihost_write(SEMIHOST_STDOUT, data, length);
20 
21 	if (ret) {
22 		return ret;
23 	}
24 
25 	return length;
26 }
27 
28 LOG_OUTPUT_DEFINE(log_output_semihost, char_out, buf, sizeof(buf));
29 
panic(struct log_backend const * const backend)30 static void panic(struct log_backend const *const backend)
31 {
32 	ARG_UNUSED(backend);
33 
34 	log_output_flush(&log_output_semihost);
35 }
36 
dropped(const struct log_backend * const backend,uint32_t cnt)37 static void dropped(const struct log_backend *const backend, uint32_t cnt)
38 {
39 	ARG_UNUSED(backend);
40 
41 	log_output_dropped_process(&log_output_semihost, cnt);
42 }
43 
process(const struct log_backend * const backend,union log_msg_generic * msg)44 static void process(const struct log_backend *const backend, union log_msg_generic *msg)
45 {
46 	ARG_UNUSED(backend);
47 
48 	uint32_t flags = log_backend_std_get_flags();
49 
50 	log_format_func_t log_output_func = log_format_func_t_get(log_format_current);
51 
52 	log_output_func(&log_output_semihost, &msg->log, flags);
53 }
54 
format_set(const struct log_backend * const backend,uint32_t log_type)55 static int format_set(const struct log_backend *const backend, uint32_t log_type)
56 {
57 	ARG_UNUSED(backend);
58 
59 	log_format_current = log_type;
60 	return 0;
61 }
62 
63 const struct log_backend_api log_backend_semihost_api = {
64 	.process = process,
65 	.panic = panic,
66 	.dropped = IS_ENABLED(CONFIG_LOG_MODE_IMMEDIATE) ? NULL : dropped,
67 	.format_set = format_set,
68 };
69 
70 LOG_BACKEND_DEFINE(log_backend_semihost, log_backend_semihost_api,
71 		   IS_ENABLED(CONFIG_LOG_BACKEND_SEMIHOST_AUTOSTART));
72