xref: /openbmc/qemu/linux-user/semihost.c (revision 004d2abe)
1 /*
2  * ARM Compatible Semihosting Console Support.
3  *
4  * Copyright (c) 2019 Linaro Ltd
5  *
6  * Currently ARM and RISC-V are unique in having support for
7  * semihosting support in linux-user. So for now we implement the
8  * common console API but just for arm and risc-v linux-user.
9  *
10  * SPDX-License-Identifier: GPL-2.0-or-later
11  */
12 
13 #include "qemu/osdep.h"
14 #include "semihosting/console.h"
15 #include "qemu.h"
16 #include "user-internals.h"
17 #include <termios.h>
18 
19 int qemu_semihosting_console_outs(CPUArchState *env, target_ulong addr)
20 {
21     int len = target_strlen(addr);
22     void *s;
23     if (len < 0){
24        qemu_log_mask(LOG_GUEST_ERROR,
25                      "%s: passed inaccessible address " TARGET_FMT_lx,
26                      __func__, addr);
27        return 0;
28     }
29     s = lock_user(VERIFY_READ, addr, (long)(len + 1), 1);
30     g_assert(s);  /* target_strlen has already verified this will work */
31     len = write(STDERR_FILENO, s, len);
32     unlock_user(s, addr, 0);
33     return len;
34 }
35 
36 /*
37  * For linux-user we can safely block. However as we want to return as
38  * soon as a character is read we need to tweak the termio to disable
39  * line buffering. We restore the old mode afterwards in case the
40  * program is expecting more normal behaviour. This is slow but
41  * nothing using semihosting console reading is expecting to be fast.
42  */
43 int qemu_semihosting_console_read(CPUState *cs, void *buf, int len)
44 {
45     int ret;
46     struct termios old_tio, new_tio;
47 
48     /* Disable line-buffering and echo */
49     tcgetattr(STDIN_FILENO, &old_tio);
50     new_tio = old_tio;
51     new_tio.c_lflag &= (~ICANON & ~ECHO);
52     new_tio.c_cc[VMIN] = 1;
53     new_tio.c_cc[VTIME] = 0;
54     tcsetattr(STDIN_FILENO, TCSANOW, &new_tio);
55 
56     ret = fread(buf, 1, len, stdin);
57 
58     /* restore config */
59     tcsetattr(STDIN_FILENO, TCSANOW, &old_tio);
60 
61     return ret;
62 }
63 
64 int qemu_semihosting_console_write(void *buf, int len)
65 {
66     return fwrite(buf, 1, len, stderr);
67 }
68