qualcomm/qbox
Loading...
Searching...
No Matches
char_backend_stdio.h
1/*
2 * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All Rights Reserved.
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7#ifndef _GS_UART_BACKEND_STDIO_H_
8#define _GS_UART_BACKEND_STDIO_H_
9
10#include <systemc>
11#include <tlm.h>
12#include <tlm_utils/simple_target_socket.h>
13
14#include <unistd.h>
15
16#include <async_event.h>
17#include <uutils.h>
18#include <ports/biflow-socket.h>
19#include <module_factory_registery.h>
20#include <queue>
21#include <signal.h>
22#include <regex>
23#include <atomic>
24#include <cstdlib>
25
26// TODO convert scp warn to scp fatal
27
28#ifdef _WIN32
29#include <windows.h>
30typedef HANDLE descriptor_t;
31typedef DWORD console_mode_t;
32#else
33#include <termios.h>
34#include <poll.h>
35typedef int descriptor_t;
36typedef struct termios console_mode_t;
37#endif // _WIN32
38
39#define RCV_POLL_TIMEOUT_MS 300
40
41class char_backend_stdio : public sc_core::sc_module
42{
43protected:
44 cci::cci_param<bool> p_read_write;
45 cci::cci_param<std::string> p_expect;
46 cci::cci_param<std::string> p_highlight;
47
48private:
49 std::atomic_bool m_running;
50 std::thread rcv_thread_id;
51 std::atomic<bool> c_flag;
52 SCP_LOGGER();
53 std::string line;
54 std::string ecmd;
55 sc_core::sc_event ecmdev;
56 bool processing = false;
57 static descriptor_t stdin_fd;
58
59#ifdef _WIN32
60 const static size_t input_buffer_size = 128;
61 INPUT_RECORD irInBuf[input_buffer_size];
62#endif
63
64public:
66 static console_mode_t old_console_mode;
67 static bool old_console_mode_valid;
68
69private:
70#ifdef _WIN32
71 static void restore_old_mode()
72 {
73 BOOL res = SetConsoleMode(stdin_fd, old_console_mode);
74 if (!res) {
75 set_default_mode();
76 }
77 }
78
79 static void set_raw_mode()
80 {
81 if (!old_console_mode_valid && GetConsoleMode(stdin_fd, &old_console_mode)) {
82 old_console_mode_valid = true;
83 }
84
85 BOOL res = SetConsoleMode(stdin_fd, ENABLE_PROCESSED_INPUT);
86 }
87
88 static void set_default_mode()
89 {
90 SetConsoleMode(stdin_fd, ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
91 }
92
93 descriptor_t get_stdin_descriptor()
94 {
95 descriptor_t stdin_file_descriptor = GetStdHandle(STD_INPUT_HANDLE);
96 if (stdin_file_descriptor == INVALID_HANDLE_VALUE) {
97 SCP_WARN(())("char_backend_stdio: Failed to get standard input descriptor. Error: {}", GetLastError());
98 }
99
100 return stdin_file_descriptor;
101 }
102
103 void enqueue_multiple(const INPUT_RECORD irInBuf[], const DWORD cNumRead)
104 {
105 for (DWORD i = 0; i < cNumRead; ++i) {
106 const INPUT_RECORD& record = irInBuf[i];
107 if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) {
108 if (record.Event.KeyEvent.uChar.AsciiChar == 0x1c) {
109 raise(SIGBREAK);
110 return;
111 }
112 enqueue(record.Event.KeyEvent.uChar.AsciiChar);
113 }
114 }
115 }
116
117 void rcv_thread()
118 {
119 DWORD cNumRead = 0;
120
121 while (m_running) {
122 DWORD waitResult = WaitForSingleObject(stdin_fd, RCV_POLL_TIMEOUT_MS);
123
124 if (waitResult == WAIT_TIMEOUT) {
125 if (c_flag) {
126 c_flag = false;
127 enqueue('\x03');
128 }
129 continue;
130 } else if (waitResult == WAIT_OBJECT_0) {
131 if (ReadConsoleInput(stdin_fd, irInBuf, input_buffer_size, &cNumRead)) {
132 enqueue_multiple(irInBuf, cNumRead);
133 } else {
134 SCP_WARN(())("char_backend_stdio: Failed to read console input. Error: {}", GetLastError());
135 }
136 } else {
137 break;
138 }
139 }
140 }
141#else
142 descriptor_t get_stdin_descriptor() { return STDIN_FILENO; } /* stdin */
143
144 static void restore_old_mode()
145 {
146 if (tcsetattr(stdin_fd, TCSANOW, &old_console_mode) == -1) {
147 set_default_mode();
148 }
149 }
150
151 static void set_raw_mode()
152 {
153 console_mode_t tty;
154 tcgetattr(stdin_fd, &tty);
155 if (!old_console_mode_valid) {
156 old_console_mode = tty;
157 old_console_mode_valid = true;
158 }
159 tty.c_lflag &= ~(ECHO | ICANON | IEXTEN);
160 tcsetattr(stdin_fd, TCSANOW, &tty);
161 }
162
163 static void set_default_mode()
164 {
165 console_mode_t tty;
166 tcgetattr(stdin_fd, &tty);
167 tty.c_lflag |= ECHO | ICANON | IEXTEN;
168 tcsetattr(stdin_fd, TCSANOW, &tty);
169 }
170
171 void rcv_thread()
172 {
173 int fd = STDIN_FILENO;
174 struct pollfd rcv_monitor;
175 rcv_monitor.fd = fd;
176 rcv_monitor.events = POLLIN;
177
178 while (m_running) {
179 int ret = poll(&rcv_monitor, 1, RCV_POLL_TIMEOUT_MS);
180 if ((ret == -1 && errno == EINTR) || (ret == 0) /*timeout*/) {
181 if (c_flag) {
182 c_flag = false;
183 enqueue('\x03');
184 }
185 continue;
186 } else if (rcv_monitor.revents & POLLIN) {
187 char c;
188 int r = read(fd, &c, 1);
189 if (r == 1) {
190 enqueue(c);
191 }
192 if (r == 0) {
193 break;
194 }
195 } else {
196 break;
197 }
198 }
199 }
200#endif
201
202public:
203 void catch_fn(int signo) {}
204
205 static void tty_reset()
206 {
207 if (old_console_mode_valid) {
208 restore_old_mode();
209 } else {
210 set_default_mode();
211 }
212 }
213
214 // trim from end of string (right)
215 std::string& rtrim(std::string& s)
216 {
217 const char* t = "\n\r\f\v";
218 s.erase(s.find_last_not_of(t) + 1);
219 return s;
220 }
221 std::string getecmdstr(const std::string& cmd)
222 {
223 return ecmd.substr(cmd.length(), ecmd.find_first_of("\n") - cmd.length());
224 }
225 void process()
226 {
227 processing = true;
228 expect_process();
229 }
230 void expect_process()
231 {
232 if (!processing) return;
233 const std::string expectstr = "expect ";
234 const std::string sendstr = "send ";
235 const std::string waitstr = "wait ";
236 const std::string exitstr = "exit";
237 do {
238 if (ecmd.substr(0, expectstr.length()) == expectstr) {
239 std::string str = getecmdstr(expectstr);
240 std::regex restr(str);
241 if (std::regex_search(line, restr)) {
242 SCP_WARN(())("Found expect string {}", rtrim(line));
243 ecmd.erase(0, ecmd.find_first_of("\n"));
244 if (ecmd != "") ecmd.erase(0, 1);
245 if (ecmd.substr(0, expectstr.length()) == expectstr) break;
246 continue;
247 }
248 }
249 if (ecmd.substr(0, sendstr.length()) == sendstr) {
250 SCP_WARN(())("Sending expect string {}", getecmdstr(sendstr));
251 for (char c : getecmdstr(sendstr)) {
252 enqueue(c);
253 }
254 enqueue('\n');
255 ecmd.erase(0, ecmd.find_first_of("\n"));
256 if (ecmd != "") ecmd.erase(0, 1);
257 continue;
258 }
259 if (ecmd.substr(0, waitstr.length()) == waitstr) {
260 SCP_WARN(())("Expect waiting {}s", getecmdstr(waitstr));
261 processing = false;
262 ecmdev.notify(stod(getecmdstr(waitstr)), sc_core::SC_SEC);
263 ecmd.erase(0, ecmd.find_first_of("\n"));
264 if (ecmd != "") ecmd.erase(0, 1);
265 break;
266 }
267 if (ecmd.substr(0, exitstr.length()) == exitstr) {
268 SCP_WARN(())("Expect caused exit");
269 sc_core::sc_stop();
270 }
271 break;
272 } while (true);
273 }
274
275 /*
276 * char_backend_stdio constructor
277 * Parameters:
278 * \param read_write bool : when set to true, accept input from STDIO
279 * \param expect String : An 'expect' like string of commands, each command should be separated by \n
280 * The acceptable commands are:
281 * expect [string] : dont process any more commands until the "string" is seen on the output (STDIO)
282 * send [string] : send "string" to the input buffer (NB this will happen whether of not read_write is set
283 * wait [float] : Wait for "float" (simulated) seconds, until processing continues.
284 * exit : Cause the simulation to terminate normally.
285 */
286 char_backend_stdio(sc_core::sc_module_name name)
287 : sc_core::sc_module(name)
288 , p_read_write("read_write", true, "read_write if true start rcv_thread")
289 , p_expect("expect", "", "string of expect commands")
290 , p_highlight("ansi_highlight", "", "ANSI highlight code to use for output, default bold")
291 , socket("biflow_socket")
292 , m_running(true)
293 , c_flag(false)
294 {
295 SCP_TRACE(()) << "CharBackendStdio constructor";
296
297 stdin_fd = get_stdin_descriptor();
298
299 ecmd = p_expect;
300 SC_METHOD(process);
301 sensitive << ecmdev;
302 if (p_expect.get_value() != "") {
303 ecmd = p_expect;
304 processing = true;
305 SCP_WARN(())("Processing expect string {}", ecmd);
306 }
307
308 gs::SigHandler::get().register_on_exit_cb(std::string(this->name()) + ".char_backend_stdio::tty_reset",
309 tty_reset);
310 gs::SigHandler::get().add_sigint_handler(gs::Handler_CB::PASS);
311 gs::SigHandler::get().register_handler(std::string(this->name()) + ".char_backend_stdio::SIGINT_handler",
312 [&](int signo) {
313 if (signo == SIGINT) {
314 c_flag = true;
315 }
316 });
317 if (p_read_write) rcv_thread_id = std::thread(&char_backend_stdio::rcv_thread, this);
318
319 socket.register_b_transport(this, &char_backend_stdio::writefn);
320 std::atexit(tty_reset);
321 }
322
323 void end_of_elaboration() { socket.can_receive_any(); }
324
325 void enqueue(char c) { socket.enqueue(c); }
326
327 void writefn(tlm::tlm_generic_payload& txn, sc_core::sc_time& t)
328 {
329 uint8_t* data = txn.get_data_ptr();
330 if (!p_highlight.get_value().empty()) std::cout << p_highlight.get_value();
331 for (int i = 0; i < txn.get_streaming_width(); i++) {
332 putchar(data[i]);
333 if ((char)data[i] == '\n') {
334 expect_process();
335 line = "";
336 } else {
337 line = line + (char)data[i];
338 }
339 }
340 if (!p_highlight.get_value().empty()) std::cout << "\x1B[0m"; // ANSI color reset.
341 fflush(stdout);
342 }
343
344 void start_of_simulation()
345 {
346 if (!old_console_mode_valid) {
347 set_raw_mode();
348 }
349 }
350
351 void end_of_simulation() { tty_reset(); }
352
353 ~char_backend_stdio()
354 {
355 gs::SigHandler::get().deregister_on_exit_cb(std::string(name()) + ".char_backend_stdio::tty_reset");
356 gs::SigHandler::get().deregister_handler(std::string(name()) + ".char_backend_stdio::SIGINT_handler");
357 m_running = false;
358 if (rcv_thread_id.joinable()) rcv_thread_id.join();
359 tty_reset();
360 }
361};
362extern "C" void module_register();
363#endif
Definition biflow-socket.h:73