summaryrefslogtreecommitdiff
path: root/emulator.cpp
blob: 16059957bc69f3ea17cb832ab5a861bec57e59b9 (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
/* SPDX-License-Identifier: Unlicense
 */

#include "bus.hpp"
#include "m68k_debugging.hpp"
#include "gdbremote_parser.hpp"
#include "musashi-m68k/m68k.h"

#include <cassert>
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <cstdarg>
#include <ctime>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#if !defined(DEBUG_TRACE_INSTRUCTIONS)
#   define DEBUG_TRACE_INSTRUCTIONS 0
#endif

#define MESSAGE_BUFFER_SIZE 1024

char msg_buf[MESSAGE_BUFFER_SIZE];

static int set_socket_reuseaddr(int socket_fd)
{
    const int val = 1;
    const socklen_t len = sizeof(val);
    return setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*)&val, len);
}

static inline struct sockaddr_in sockaddr_in_any_ip_with_port(uint16_t port) {
    struct sockaddr_in server{};
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(port);
    return server;
}

static int setup_socket(uint16_t port)
{
    // This creates the socket - or quits
    const int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1) {
        perror("Could not create socket");
        return -1;
    }
    // Make TCP port reusable in case of kill or crash.
    // Deliberate explanation: https://stackoverflow.com/a/3233022
    if (set_socket_reuseaddr(socket_fd) == -1) {
        perror("setsockopt failed");
        close(socket_fd);
        return -1;
    }
    puts("Socket created");
    const struct sockaddr_in server = sockaddr_in_any_ip_with_port(port);
    if (bind(socket_fd, (struct sockaddr *)&server, sizeof(server)) == -1) {
        perror("Bind failed");
        close(socket_fd);
        return -1;
    }
    printf("Binding to 0.0.0.0:%u done\n", port);
    return socket_fd;
}

static inline void ConvertByteToHex(uint8_t byte, char* out)
{
    const uint8_t c1 = (byte >> 4) & 0x0f;
    const uint8_t c2 = byte& 0x0f;
    out[0] = static_cast<char>(c1 < 0xa ? c1 + '0' : c1 + ('a' - 0xa));
    out[1] = static_cast<char>(c2 < 0xa ? c2 + '0' : c2 + ('a' - 0xa));
}

static std::string CreateResponse(
        M68KDebuggingControl& m68k_debug,
        const GDBRemote::Packet& packet)
{
    using namespace GDBRemote;
    if (0) {
    } else if (packet.type == PacketType::kQueryHaltReason) {
        return "S05";
    } else if (packet.type == PacketType::kStep) {
        m68k_execute(1);
        return "S05";
    } else if (packet.type == PacketType::kSetThreadForCont) {
        return "OK";
    } else if (packet.type == PacketType::kQueryAttached) {
        return "1";
    } else if (packet.type == PacketType::kInterrupt) {
        return "OK";
    } else if (packet.type == PacketType::kReadMemory) {
        const auto * const data =
            reinterpret_cast<const PacketDataReadMemory*>(packet.data.get());
        const uint32_t offset = data->offset;
        const uint32_t length = data->length;
        auto ret_data = std::string(length * 2, '\0');
        for (uint32_t i = 0; i < length; i++) {
            const uint8_t byte = m68k_debug.Read8(i + offset);
            ConvertByteToHex(byte, &ret_data[i*2]);
        }
        return ret_data;
    } else if (packet.type == PacketType::kReadGeneralRegisters) {
        const M68KCPUState state = m68k_debug.GetCPUState();
        std::string result{};
        for (size_t i = 0; i < state.registers_count ;i++)
        {
            constexpr size_t value_size = 8;
            char value[value_size + 1]{};
            const int ret = snprintf(value, value_size + 1, "%08x", state.registers[i]);
            assert(ret == value_size);
            result += std::string(value, value_size);
        }
        return result;
    } else if (packet.type == PacketType::kContinueAskSupported) {
        return "vCont:c:s";
    }
    return "";
}

static void exit_error(const char* fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
    fprintf(stderr, "\n");
    exit(EXIT_FAILURE);
}

/* Called when the CPU pulses the RESET line */
void m68k_reset_callback(void)
{
    // TODO
}

/* Called when the CPU acknowledges an interrupt */
int m68k_irq_ack(int level)
{
    (void) level;
    // TODO
    exit_error("IRQ ack");
    return M68K_INT_ACK_SPURIOUS;
}

static void make_hex(char* buff, unsigned int pc, unsigned int length)
{
    char* ptr = buff;

    for (;length>0;length -= 2)
    {
        sprintf(ptr, "%04x", m68k_read_disassembler_16(pc));
        pc += 2;
        ptr += 4;
        if (length > 2)
            *ptr++ = ' ';
    }
}

void m68k_instr_callback(int pc)
{
    if (!DEBUG_TRACE_INSTRUCTIONS)
        return;
    char buff[100];
    unsigned int instr_size =
        m68k_disassemble(buff, pc, M68K_CPU_TYPE_68000);
    char buff2[100];
    make_hex(buff2, pc, instr_size);
    printf("  %08X: %-20s: %s\n", pc, buff2, buff);
    fflush(stdout);
}

int emulator(M68KDebuggingControl& m68k_debug)
{
    const int port = 3333;
    const int socket_fd = setup_socket(port);
    if (socket_fd == -1)
        return EXIT_FAILURE;
    printf("Listening TCP 0.0.0.0:%u\n", port);
    listen(socket_fd, 4); // Mark socket as listener
    struct sockaddr client_address;
    socklen_t address_len;
    const int conn_fd = accept(socket_fd, &client_address, &address_len);
    if (conn_fd == -1) {
        perror("Accept failed");
        close(socket_fd);
        return EXIT_FAILURE;
    }
    puts("Connection accepted");
    GDBRemote::ExchangeContext exchange_ctx{};
    ssize_t read_size;
    while ((read_size = recv(conn_fd, msg_buf, MESSAGE_BUFFER_SIZE, 0)) > 0) {
        for (size_t i = 0; i < static_cast<size_t>(read_size); i++) {
            const auto res = exchange_ctx.Consume(msg_buf[i]);
            if (res == nullptr) continue;
            if (res->packet.length() > 0) {
                if (0) printf("<- \"%s\"\n", exchange_ctx.GetLastPacket().c_str());
                const auto packet = GDBRemote::Packet::Parse(res->packet);
                if (0) printf(
                        "   Packet type: \"%s\"\n",
                        GDBRemote::Packet::PacketTypeToString(packet.type));
            }
            if (res->ack.length() > 0) {
                if (0) printf("-> \"%s\"\n", res->ack.c_str());
                if (send(conn_fd, &res->ack[0], res->ack.length(), 0) == -1)
                    perror("Send failed (ack/nak)");
            }
            if (res->packet.length() > 0) {
                const auto packet = GDBRemote::Packet::Parse(res->packet);
                const auto response =
                    exchange_ctx.WrapDataToSend(CreateResponse(m68k_debug, packet));
                if (0) printf("-> \"%s\"\n", response.c_str());
                if (send(conn_fd, &response[0], response.length(), 0) == -1)
                    perror("Send failed (response)");
            }
        }
        memset(msg_buf, '\0', MESSAGE_BUFFER_SIZE);
    }
    if (read_size == 0) {
        puts("Client disconnected");
    } else if (read_size == -1) {
        perror("Recv failed");
    }
    close(socket_fd);
    return 0;
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        printf("Usage: sim <program file>\n");
        exit(-1);
    }

    FILE* const fhandle = fopen(argv[1], "rb");

    if (fhandle == NULL)
        exit_error("Unable to open %s", argv[1]);

    const size_t fread_ret = fread(g_rom, 1, ROM_SIZE, fhandle);
    if (fread_ret <= 0)
        exit_error("Error reading %s", argv[1]);
    printf("Read into ROM %zu bytes\n", fread_ret);

    m68k_init();
    m68k_set_cpu_type(M68K_CPU_TYPE_68000);
    m68k_pulse_reset();

    M68KDebuggingControl m68k_debug{};
    emulator(m68k_debug);
    while (0)
    {
        // Values to execute determine the interleave rate.
        // Smaller values allow for more accurate interleaving with multiple
        // devices/CPUs but is more processor intensive.
        // 100000 is usually a good value to start at, then work from there.

        // Note that I am not emulating the correct clock speed!
        m68k_execute(100000);
    }

    return 0;
}