1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26#include "qemu/osdep.h"
27#include "qemu-common.h"
28#include "sysemu/char.h"
29
30#define BUF_SIZE 32
31
32typedef struct {
33 CharDriverState *chr;
34 uint8_t in_buf[32];
35 int in_buf_used;
36} TestdevCharState;
37
38
39static int testdev_eat_packet(TestdevCharState *testdev)
40{
41 const uint8_t *cur = testdev->in_buf;
42 int len = testdev->in_buf_used;
43 uint8_t c;
44 int arg;
45
46#define EAT(c) do { \
47 if (!len--) { \
48 return 0; \
49 } \
50 c = *cur++; \
51} while (0)
52
53 EAT(c);
54
55 while (isspace(c)) {
56 EAT(c);
57 }
58
59 arg = 0;
60 while (isdigit(c)) {
61 arg = arg * 10 + c - '0';
62 EAT(c);
63 }
64
65 while (isspace(c)) {
66 EAT(c);
67 }
68
69 switch (c) {
70 case 'q':
71 exit((arg << 1) | 1);
72 break;
73 default:
74 break;
75 }
76 return cur - testdev->in_buf;
77}
78
79
80static int testdev_write(CharDriverState *chr, const uint8_t *buf, int len)
81{
82 TestdevCharState *testdev = chr->opaque;
83 int tocopy, eaten, orig_len = len;
84
85 while (len) {
86
87 tocopy = MIN(len, BUF_SIZE - testdev->in_buf_used);
88
89 memcpy(testdev->in_buf + testdev->in_buf_used, buf, tocopy);
90 testdev->in_buf_used += tocopy;
91 buf += tocopy;
92 len -= tocopy;
93
94
95 while (testdev->in_buf_used > 0 &&
96 (eaten = testdev_eat_packet(testdev)) > 0) {
97 memmove(testdev->in_buf, testdev->in_buf + eaten,
98 testdev->in_buf_used - eaten);
99 testdev->in_buf_used -= eaten;
100 }
101 }
102 return orig_len;
103}
104
105static void testdev_close(struct CharDriverState *chr)
106{
107 TestdevCharState *testdev = chr->opaque;
108
109 g_free(testdev);
110}
111
112static CharDriverState *chr_testdev_init(const char *id,
113 ChardevBackend *backend,
114 ChardevReturn *ret,
115 Error **errp)
116{
117 TestdevCharState *testdev;
118 CharDriverState *chr;
119
120 testdev = g_new0(TestdevCharState, 1);
121 testdev->chr = chr = g_new0(CharDriverState, 1);
122
123 chr->opaque = testdev;
124 chr->chr_write = testdev_write;
125 chr->chr_close = testdev_close;
126
127 return chr;
128}
129
130static void register_types(void)
131{
132 register_char_driver("testdev", CHARDEV_BACKEND_KIND_TESTDEV, NULL,
133 chr_testdev_init);
134}
135
136type_init(register_types);
137