summaryrefslogtreecommitdiff
path: root/gdbremote_parser.cpp
blob: 641590fdda7721a9ad3b89b31276285298103e0e (plain)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/* SPDX-License-Identifier: Unlicense
 */

#include "gdbremote_parser.hpp"

#include <cctype>
#include <cassert>
#include <cstring>

using namespace GDBRemote;

enum class TokenType: uint8_t {
    kUnknown = 0,
    kSeparatorComma,
    kSeparatorColon,
    kSeparatorSemicolon,
    kNumeric,
    kHexNumeric,
    kArbitrary,
};

static inline bool isseparator(uint8_t byte)
{
    return ':' == byte || ';' == byte || ',' == byte;
}

static inline bool IsTokenTypeSeparator(TokenType token_type)
{
    return token_type == TokenType::kSeparatorColon ||
        token_type == TokenType::kSeparatorComma ||
        token_type == TokenType::kSeparatorSemicolon;
}

static inline TokenType separatorTypeFromByte(uint8_t byte)
{
    if (':' == byte) return TokenType::kSeparatorColon;
    if (';' == byte) return TokenType::kSeparatorSemicolon;
    return TokenType::kSeparatorComma;
}

struct Token {
    TokenType type{};
    std::string data{};

    static std::vector<Token> Tokenize(std::string packet_data)
    {
        if (packet_data.length() == 0) return std::vector<Token>{};
        std::vector<Token> tokens{};
        TokenType type{};
        size_t i{}, offset{};
        for (; i < packet_data.length(); i++) {
            assert(type != TokenType::kSeparatorColon);
            assert(type != TokenType::kSeparatorSemicolon);
            assert(type != TokenType::kSeparatorComma);
            const uint8_t byte = packet_data[i];
            if (isseparator(byte)) {
                if (i > offset) {
                    assert(type != TokenType::kUnknown);
                    tokens.push_back(Token{type, packet_data.substr(offset, i - offset)});
                    offset = i;
                }
                tokens.push_back(Token{
                        separatorTypeFromByte(byte),
                        packet_data.substr(offset, 1),
                        });
                offset++;
                type = TokenType::kUnknown;
            } else if (isdigit(byte)) {
                if (type == TokenType::kUnknown) {
                    type = TokenType::kNumeric;
                }
            } else if (isxdigit(byte)) {
                if (type != TokenType::kArbitrary) {
                    type = TokenType::kHexNumeric;
                }
            } else {
                type = TokenType::kArbitrary;
            }
        }
        if (i > offset) {
            assert(type != TokenType::kUnknown);
            tokens.push_back(Token{type, packet_data.substr(offset, i - offset)});
        }
        return tokens;
    }
};

struct Command {
    std::string name;
    Packet (*parse)(const std::vector<Token>&&);
    static Packet parseNone(const std::vector<Token>&&)
    {
        return Packet::None();
    }
    static Packet parseQuerySupported(const std::vector<Token>&&)
    {
        // TODO arguments
        return Packet{PacketType::kQuerySupported};
    }
    static Packet parseQueryHaltReason(const std::vector<Token>&&)
    {
        return Packet{PacketType::kQueryHaltReason};
    }
    static Packet parseQueryC(const std::vector<Token>&&)
    {
        // TODO arguments
        return Packet{PacketType::kQueryC};
    }
    static Packet parseQueryFThreadInfo(const std::vector<Token>&&)
    {
        return Packet{PacketType::kQueryFThreadInfo};
    }
    static Packet parseQuerySThreadInfo(const std::vector<Token>&&)
    {
        return Packet{PacketType::kQuerySThreadInfo};
    }
    static Packet parseQueryRTOSThreadInfo(const std::vector<Token>&&)
    {
        // TODO arguments
        return Packet{PacketType::kQueryRTOSThreadInfo};
    }
    static Packet parseQueryAttached(const std::vector<Token>&&)
    {
        // TODO arguments
        return Packet{PacketType::kQueryAttached};
    }
    static Packet parseQueryTraceStatus(const std::vector<Token>&&)
    {
        return Packet{PacketType::kQueryTraceStatus};
    }
    static Packet parseSetThreadForCont(const std::vector<Token>&&)
    {
        // TODO arguments
        return Packet{PacketType::kSetThreadForCont};
    }
    static Packet parseSetThreadForOps(const std::vector<Token>&&)
    {
        // TODO arguments
        return Packet{PacketType::kSetThreadForOps};
    }
    static Packet parseMustReplyEmpty(const std::vector<Token>&&)
    {
        return Packet{PacketType::kVMustReplyEmpty};
    }
    static Packet parseEnableExtendedMode(const std::vector<Token>&&)
    {
        return Packet{PacketType::kEnableExtendedMode};
    }
    static Packet parseInterrupt(const std::vector<Token>&&)
    {
        return Packet{PacketType::kInterrupt};
    }
    static Packet parseContinueVCont(const std::vector<Token>&& tokens)
    {
        const std::string first = tokens[0].data;
        constexpr size_t command_len = strlen("vCont");
        // Check if it is "vCont?" command
        if (first.length() > command_len && first[command_len] == '?') {
            return Packet{PacketType::kContinueAskSupported};
        }
        // TODO arguments
        return Packet{PacketType::kContinue};
    }
    static Packet parseContinue(const std::vector<Token>&&)
    {
        return Packet{PacketType::kContinue};
    }
    static Packet parseReadMemory(const std::vector<Token>&& tokens)
    {
        if (tokens.size() < 3 ||
                tokens[0].type != TokenType::kArbitrary ||
                !IsTokenTypeSeparator(tokens[1].type) ||
                tokens[2].type != TokenType::kNumeric)
        {
            return Packet::None();
        }
        constexpr size_t command_len = strlen("m");
        const std::string first = tokens[0].data;
        const std::string second = tokens[2].data;
        const uint32_t offset = strtol(
                    first.substr(command_len, first.length()-command_len).c_str(),
                    nullptr,
                    16);
        const uint32_t lenght = strtol(second.c_str(), nullptr, 16);
        return Packet{
            PacketType::kReadMemory,
            std::make_unique<const PacketDataReadMemory>(offset, lenght),
        };
    }
    static Packet parseReadGeneralRegisters(const std::vector<Token>&&)
    {
        return Packet{PacketType::kReadGeneralRegisters};
    }
    static Packet parseStep(const std::vector<Token>&&)
    {
        return Packet{PacketType::kStep};
    }
};

static const Command commands[] = {
    { "qSupported",         Command::parseQuerySupported },
    { "?",                  Command::parseQueryHaltReason },
    { "qC",                 Command::parseQueryC },
    { "qfThreadInfo",       Command::parseQueryFThreadInfo },
    { "qsThreadInfo",       Command::parseQuerySThreadInfo },
    { "qL",                 Command::parseQueryRTOSThreadInfo },
    { "qAttached",          Command::parseQueryAttached },
    { "qTStatus",           Command::parseQueryTraceStatus },
    { "Hc",                 Command::parseSetThreadForCont },
    { "Hg",                 Command::parseSetThreadForOps },
    { "vMustReplyEmpty",    Command::parseMustReplyEmpty },
    { "!",                  Command::parseEnableExtendedMode },
    { "\x03",               Command::parseInterrupt },
    { "vCtrlC",             Command::parseInterrupt },
    { "vCont",              Command::parseContinueVCont },
    { "c",                  Command::parseContinue },
    { "m",                  Command::parseReadMemory },
    { "g",                  Command::parseReadGeneralRegisters },
    { "s",                  Command::parseStep },
};

Packet Packet::Parse(std::string packet_data)
{
    const auto tokens = Token::Tokenize(packet_data);
    if (tokens.size() == 0) {
        printf("Warning: no tokens to parse\n");
        return Packet::None();
    }
    const auto first_token = tokens[0];
    for (const auto& command: commands) {
        const auto cmdlen = command.name.length();
        const auto toklen = first_token.data.length();
        // Make sure first token fully includes the command from the beginning
        // and not necessary fully equals to it.
        // TODO tokenize as if the command is always a separate token
        if (cmdlen <= toklen && 0 == memcmp(
                    &command.name[0], &first_token.data[0], cmdlen))
        {
            return command.parse(std::move(tokens));
        }
    }
    return Packet::None();
}

static inline uint8_t parseChecksumFromHexChars(uint8_t first, uint8_t second)
{
    // Assume, that given bytes are valid hex digits in ASCII
    first = ((first & 0x40) ? (first + 9) : first) & 0x0f;
    second = ((second & 0x40) ? (second + 9) : second) & 0x0f;
    return ((first << 4) | second) & 0xff;
}

std::unique_ptr<ExchangeResult> ExchangeContext::Consume(uint8_t byte)
{
    _last_packet += byte;
    switch (_parsing_state) {
    case ParsingState::kIdle:
        if (byte == '$') {
            transit(ParsingState::kPacketData);
        } else if (byte == 0x03) {
            _last_packet = std::string(1, 0x03);
            return ExchangeResult::Ack(_last_packet);
        }
        break;
    case ParsingState::kPacketData:
        if (byte == '#') {
            transit(ParsingState::kChecksum1);
        } else {
            _checksum = (_checksum + byte) & 0xff;
            _packet_data += byte;
        }
        break;
    case ParsingState::kPacketDataBinSecond:
        // TODO escaped and binary data
        break;
    case ParsingState::kChecksum1:
        if (isxdigit(byte)) {
            transit(ParsingState::kChecksum2);
            _given_checksum_first_byte = byte;
        } else {
            transit(ParsingState::kIdle);
            return ExchangeResult::Nak();
        }
        break;
    case ParsingState::kChecksum2:
        const uint8_t checksum = _checksum;
        std::string packet_data(std::move(_packet_data));
        transit(ParsingState::kIdle);
        if (isxdigit(byte)) {
            const uint8_t given_checksum =
                parseChecksumFromHexChars(_given_checksum_first_byte, byte);
            if (given_checksum == checksum) {
                return ExchangeResult::Ack(packet_data);
            } else {
                printf(
                        "Checksum mismatch: received=%02x, expected=%02x\n",
                        given_checksum, checksum);
                printf("Packet data: \"%s\"\n", packet_data.c_str());
                return ExchangeResult::Nak();
            }
        } else {
            return ExchangeResult::Nak();
        }
        break;
    }
    return nullptr;
}

static inline uint8_t CalcPacketDataChecksum(std::string packet) {
    uint8_t checksum{};
    for (const auto c: packet) {
        checksum = (checksum + c) & 0xff;
    }
    return checksum;
}

std::string ExchangeContext::WrapDataToSend(std::string packet)
{
    const uint8_t checksum = CalcPacketDataChecksum(packet);
    const uint8_t c1 = (checksum >> 4) & 0x0f;
    const uint8_t c2 = checksum& 0x0f;
    const char checksum_str[2] = {
        static_cast<char>(c1 < 0xa ? c1 + '0' : c1 + ('a' - 0xa)),
        static_cast<char>(c2 < 0xa ? c2 + '0' : c2 + ('a' - 0xa)),
    };
    return "$" + packet + "#" + std::string(checksum_str, 2);
}

void ExchangeContext::transit(ParsingState new_state)
{
    if (0) {
        printf(
                "GDBRemote ParsingState: %s -> %s\n",
                parsingStateToString(_parsing_state),
                parsingStateToString(new_state));
    }
    switch (new_state) {
    case ParsingState::kIdle:
        _checksum = 0;
        _packet_data.clear();
        break;
    case ParsingState::kPacketData:
        _last_packet = "$";
        break;
    case ParsingState::kPacketDataBinSecond:
        break;
    case ParsingState::kChecksum1:
        break;
    case ParsingState::kChecksum2:
        break;
    }
    _parsing_state = new_state;
}

const char* ExchangeContext::parsingStateToString(ParsingState state)
{
    switch (state) {
    case ParsingState::kIdle:
        return "Idle";
    case ParsingState::kPacketData:
        return "PacketData";
    case ParsingState::kPacketDataBinSecond:
        return "PacketDataBinSecond";
    case ParsingState::kChecksum1:
        return "Checksum1";
    case ParsingState::kChecksum2:
        return "Checksum2";
    }
    return "<unknown>";
}