summaryrefslogtreecommitdiffstats
path: root/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/core/iwasm/libraries/debug-engine/packets.c
blob: 1bdb3d2ce8de50b9482768b21ed2c3de7ea4256a (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
/*
 * Copyright (C) 2021 Ant Group.  All rights reserved.
 * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 */

#include "bh_platform.h"
#include "packets.h"
#include "gdbserver.h"

void
write_data_raw(WASMGDBServer *gdbserver, const uint8 *data, ssize_t len)
{
    ssize_t nwritten;

    nwritten = os_socket_send(gdbserver->socket_fd, data, len);
    if (nwritten < 0) {
        LOG_ERROR("Write error\n");
        exit(-2);
    }
}

void
write_hex(WASMGDBServer *gdbserver, unsigned long hex)
{
    char buf[32];
    size_t len;

    len = snprintf(buf, sizeof(buf) - 1, "%02lx", hex);
    write_data_raw(gdbserver, (uint8 *)buf, len);
}

void
write_packet_bytes(WASMGDBServer *gdbserver, const uint8 *data,
                   size_t num_bytes)
{
    uint8 checksum;
    size_t i;

    write_data_raw(gdbserver, (uint8 *)"$", 1);
    for (i = 0, checksum = 0; i < num_bytes; ++i)
        checksum += data[i];
    write_data_raw(gdbserver, (uint8 *)data, num_bytes);
    write_data_raw(gdbserver, (uint8 *)"#", 1);
    write_hex(gdbserver, checksum);
}

void
write_packet(WASMGDBServer *gdbserver, const char *data)
{
    LOG_VERBOSE("send replay:%s", data);
    write_packet_bytes(gdbserver, (const uint8 *)data, strlen(data));
}

void
write_binary_packet(WASMGDBServer *gdbserver, const char *pfx,
                    const uint8 *data, ssize_t num_bytes)
{
    uint8 *buf;
    ssize_t pfx_num_chars = strlen(pfx);
    ssize_t buf_num_bytes = 0, total_size;
    int32 i;

    total_size = 2 * num_bytes + pfx_num_chars;
    buf = wasm_runtime_malloc(total_size);
    if (!buf) {
        LOG_ERROR("Failed to allocate memory for binary packet");
        return;
    }

    memset(buf, 0, total_size);
    memcpy(buf, pfx, pfx_num_chars);
    buf_num_bytes += pfx_num_chars;

    for (i = 0; i < num_bytes; ++i) {
        uint8 b = data[i];
        switch (b) {
            case '#':
            case '$':
            case '}':
            case '*':
                buf[buf_num_bytes++] = '}';
                buf[buf_num_bytes++] = b ^ 0x20;
                break;
            default:
                buf[buf_num_bytes++] = b;
                break;
        }
    }
    write_packet_bytes(gdbserver, buf, buf_num_bytes);
    wasm_runtime_free(buf);
}