OXYGENHUB
# 69f777699a51 retro-remote-debug-controller / core / retro_control.c
11.2 KiB · C · last changed core: stub the server under emscripten too (no TCP server in the browser) 3 months ago source blame history raw
961b3c61 Andy McCall 1
/* retro_control.c — portable emulator control server. See retro_control.h
2
 * and ../SPEC.md. POSIX (Linux/macOS); on Windows the entry points are no-ops.
3
 *
4
 * One accept thread, one request in flight at a time. State reads are marshalled
5
 * to the emulator thread via retro_control_service() so they observe a
6
 * consistent machine; /step is driven cooperatively by retro_control_on_frame().
7
 */
8
#include "retro_control.h"
9
10
#include <stdio.h>
11
#include <stdlib.h>
12
#include <string.h>
13
69f77769 Andy McCall ↶ 14
#if defined(_WIN32) || defined(__EMSCRIPTEN__)
15
/* No TCP control server on Windows or in the browser (emscripten) — a localhost
16
 * socket server has no meaning there. Stub out so those builds still link. */
961b3c61 Andy McCall 17
int  retro_control_start(int port, const retro_control_backend_t *b) { (void)port; (void)b; return -1; }
18
void retro_control_service(void) {}
19
int  retro_control_running(void) { return 1; }
20
void retro_control_on_frame(void) {}
21
void retro_control_stop(void) {}
22
#else
23
24
#include <pthread.h>
25
#include <unistd.h>
26
#include <errno.h>
27
#include <signal.h>
28
#include <sys/socket.h>
29
#include <netinet/in.h>
30
#include <arpa/inet.h>
31
32
#ifndef MSG_NOSIGNAL
33
#define MSG_NOSIGNAL 0
34
#endif
35
36
#define MEM_CAP (1u << 20)   /* /mem hard cap: 1 MiB per request */
37
38
static const retro_control_backend_t *g_be = NULL;
39
static int       g_listen_fd = -1;
40
static pthread_t g_thread;
41
42
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
43
static pthread_cond_t  g_cv   = PTHREAD_COND_INITIALIZER;
44
45
/* run control: -1 free-run, 0 halted, >0 run this many frames then halt */
46
static long g_frames_to_run = -1;
47
static int  g_step_waiting  = 0;
48
49
/* single-slot marshalled request (mem / regs / screenshot) */
50
typedef enum { REQ_NONE = 0, REQ_MEM, REQ_REGS, REQ_SHOT } req_t;
51
static volatile req_t g_req = REQ_NONE;
52
static uint32_t g_req_addr, g_req_len;
53
static int32_t  g_req_bank;
54
55
static uint8_t    *g_resp_body  = NULL;
56
static size_t      g_resp_len   = 0;
57
static int         g_resp_status = 200;
58
static const char *g_resp_ctype = "application/octet-stream";
59
static int         g_resp_ready = 0;
60
61
/* ---- emulator-thread side ------------------------------------------------ */
62
63
static void build_ppm(void)
64
{
65
    retro_framebuffer_t fb;
66
    memset(&fb, 0, sizeof fb);
67
    g_be->get_framebuffer(&fb);
68
    int w = fb.width, h = fb.height;
69
    int bpp = (fb.fmt == RETRO_PIX_RGB888) ? 3 : 4;
70
71
    char hdr[64];
72
    int hl = snprintf(hdr, sizeof hdr, "P6\n%d %d\n255\n", w, h);
73
    size_t total = (size_t)hl + (size_t)3 * w * h;
74
    uint8_t *out = (uint8_t *)malloc(total ? total : 1);
75
    if (!out) { g_resp_body = NULL; g_resp_len = 0; g_resp_status = 500; return; }
76
77
    memcpy(out, hdr, hl);
78
    uint8_t *p = out + hl;
79
    const uint8_t *s = fb.pixels;
80
    for (int i = 0; i < w * h; i++) {
81
        const uint8_t *px = s + (size_t)i * bpp;
82
        if (fb.fmt == RETRO_PIX_BGRA8888) {
83
            p[0] = px[2]; p[1] = px[1]; p[2] = px[0];
84
        } else {                       /* RGB888 / RGBA8888 */
85
            p[0] = px[0]; p[1] = px[1]; p[2] = px[2];
86
        }
87
        p += 3;
88
    }
89
    g_resp_body = out;
90
    g_resp_len = total;
91
    g_resp_status = 200;
92
    g_resp_ctype = "image/x-portable-pixmap";
93
}
94
95
void retro_control_service(void)
96
{
97
    if (!g_be || g_req == REQ_NONE) return;   /* cheap unlocked fast-path */
98
99
    pthread_mutex_lock(&g_lock);
100
    switch (g_req) {
101
    case REQ_MEM: {
102
        uint32_t len = g_req_len > MEM_CAP ? MEM_CAP : g_req_len;
103
        uint8_t *buf = (uint8_t *)malloc(len ? len : 1);
104
        uint32_t got = 0;
105
        if (buf && g_be->read_mem) got = g_be->read_mem(g_req_addr, g_req_bank, len, buf, len);
106
        g_resp_body = buf; g_resp_len = got;
107
        g_resp_status = g_be->read_mem ? 200 : 501;
108
        g_resp_ctype = "application/octet-stream";
109
        break;
110
    }
111
    case REQ_REGS: {
112
        char *buf = (char *)malloc(1024);
113
        if (buf && g_be->get_regs_json) { g_be->get_regs_json(buf, 1024); }
114
        else if (buf) { buf[0] = 0; }
115
        g_resp_body = (uint8_t *)buf; g_resp_len = buf ? strlen(buf) : 0;
116
        g_resp_status = g_be->get_regs_json ? 200 : 501;
117
        g_resp_ctype = "application/json";
118
        break;
119
    }
120
    case REQ_SHOT:
121
        if (g_be->get_framebuffer) build_ppm();
122
        else { g_resp_body = NULL; g_resp_len = 0; g_resp_status = 501; }
123
        break;
124
    default: break;
125
    }
126
    g_req = REQ_NONE;
127
    g_resp_ready = 1;
128
    pthread_cond_broadcast(&g_cv);
129
    pthread_mutex_unlock(&g_lock);
130
}
131
132
int retro_control_running(void)
133
{
134
    if (!g_be) return 1;
135
    pthread_mutex_lock(&g_lock);
136
    long f = g_frames_to_run;
137
    pthread_mutex_unlock(&g_lock);
138
    return f != 0;
139
}
140
141
void retro_control_on_frame(void)
142
{
143
    if (!g_be) return;
144
    pthread_mutex_lock(&g_lock);
145
    if (g_frames_to_run > 0) {
146
        g_frames_to_run--;
147
        if (g_frames_to_run == 0 && g_step_waiting) {
148
            g_step_waiting = 0;
149
            g_resp_ready = 1;
150
            pthread_cond_broadcast(&g_cv);
151
        }
152
    }
153
    pthread_mutex_unlock(&g_lock);
154
}
155
156
/* ---- server-thread side -------------------------------------------------- */
157
158
static void write_all(int fd, const void *buf, size_t len)
159
{
160
    const char *p = (const char *)buf;
161
    while (len) {
162
        ssize_t w = send(fd, p, len, MSG_NOSIGNAL);
163
        if (w <= 0) return;
164
        p += w; len -= (size_t)w;
165
    }
166
}
167
168
static void send_http(int fd, int status, const char *ctype,
169
                      const uint8_t *body, size_t len)
170
{
171
    const char *reason =
172
        status == 200 ? "OK" :
173
        status == 400 ? "Bad Request" :
174
        status == 404 ? "Not Found" :
175
        status == 405 ? "Method Not Allowed" :
176
        status == 501 ? "Not Implemented" : "Error";
177
    char hdr[256];
178
    int hl = snprintf(hdr, sizeof hdr,
179
        "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\n"
180
        "Connection: close\r\nAccess-Control-Allow-Origin: *\r\n\r\n",
181
        status, reason, ctype, len);
182
    write_all(fd, hdr, hl);
183
    if (body && len) write_all(fd, body, len);
184
}
185
186
static void send_json(int fd, int status, const char *json)
187
{
188
    send_http(fd, status, "application/json", (const uint8_t *)json, strlen(json));
189
}
190
191
/* value of query key, decimal or 0x-hex (strtol base 0); def if absent. */
192
static long query_long(const char *q, const char *key, long def)
193
{
194
    size_t kl = strlen(key);
195
    const char *p = q;
196
    while (p && *p) {
197
        if (!strncmp(p, key, kl) && p[kl] == '=')
198
            return strtol(p + kl + 1, NULL, 0);
199
        p = strchr(p, '&');
200
        if (p) p++;
201
    }
202
    return def;
203
}
204
205
/* marshal a read to the emulator thread, wait, send the response. */
206
static void do_marshalled(int fd, req_t r)
207
{
208
    pthread_mutex_lock(&g_lock);
209
    g_resp_ready = 0; g_resp_body = NULL; g_resp_len = 0;
210
    g_req = r;
211
    while (!g_resp_ready) pthread_cond_wait(&g_cv, &g_lock);
212
    uint8_t *body = g_resp_body; size_t len = g_resp_len;
213
    int st = g_resp_status; const char *ct = g_resp_ctype;
214
    g_resp_body = NULL;
215
    pthread_mutex_unlock(&g_lock);
216
217
    send_http(fd, st, ct, body, len);
218
    free(body);
219
}
220
221
static void do_status(int fd)
222
{
223
    pthread_mutex_lock(&g_lock);
224
    long f = g_frames_to_run;
225
    pthread_mutex_unlock(&g_lock);
226
    unsigned long long fc = g_be->get_frame_count ? g_be->get_frame_count() : 0;
227
    char buf[320];
228
    snprintf(buf, sizeof buf,
229
        "{\"contract\":\"%s\",\"emulator\":\"%s\",\"platform\":\"%s\","
230
        "\"frame\":%llu,\"paused\":%s,\"running\":true}",
231
        RETRO_CONTROL_CONTRACT,
232
        g_be->emulator ? g_be->emulator : "",
233
        g_be->platform ? g_be->platform : "",
234
        fc, (f == 0) ? "true" : "false");
235
    send_json(fd, 200, buf);
236
}
237
238
static void do_step(int fd, const char *query)
239
{
240
    long n = query_long(query, "frames", 1);
241
    if (n < 1) n = 1;
242
    pthread_mutex_lock(&g_lock);
243
    g_frames_to_run = n;
244
    g_step_waiting = 1;
245
    g_resp_ready = 0;
246
    while (!g_resp_ready) pthread_cond_wait(&g_cv, &g_lock);
247
    pthread_mutex_unlock(&g_lock);
248
249
    unsigned long long fc = g_be->get_frame_count ? g_be->get_frame_count() : 0;
250
    char buf[64];
251
    snprintf(buf, sizeof buf, "{\"frame\":%llu}", fc);
252
    send_json(fd, 200, buf);
253
}
254
255
static void do_setrun(int fd, long v, int paused)
256
{
257
    pthread_mutex_lock(&g_lock);
258
    g_frames_to_run = v;
259
    pthread_mutex_unlock(&g_lock);
260
    send_json(fd, 200, paused ? "{\"paused\":true}" : "{\"paused\":false}");
261
}
262
263
static void handle_conn(int fd)
264
{
265
    char req[2048];
266
    size_t n = 0;
267
    while (n < sizeof(req) - 1) {
268
        ssize_t r = recv(fd, req + n, sizeof(req) - 1 - n, 0);
269
        if (r <= 0) break;
270
        n += (size_t)r;
271
        if (strstr(req, "\r\n\r\n")) break;
272
    }
273
    req[n] = 0;
274
275
    char method[8] = {0}, target[1024] = {0};
276
    if (sscanf(req, "%7s %1023s", method, target) != 2) {
277
        send_json(fd, 400, "{\"error\":\"bad request\"}");
278
        return;
279
    }
280
    char *q = strchr(target, '?');
281
    const char *query = "";
282
    if (q) { *q = 0; query = q + 1; }
283
    int is_post = !strcmp(method, "POST");
284
285
    if (!strcmp(target, "/status"))          { do_status(fd); return; }
286
    if (!strcmp(target, "/regs"))            { do_marshalled(fd, REQ_REGS); return; }
287
    if (!strcmp(target, "/screenshot"))      { do_marshalled(fd, REQ_SHOT); return; }
288
    if (!strcmp(target, "/mem")) {
289
        g_req_addr = (uint32_t)query_long(query, "addr", 0);
290
        g_req_len  = (uint32_t)query_long(query, "len", 0);
291
        g_req_bank = (int32_t)query_long(query, "bank", -1);
292
        do_marshalled(fd, REQ_MEM);
293
        return;
294
    }
295
    if (!strcmp(target, "/step")) {
296
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
297
        do_step(fd, query); return;
298
    }
299
    if (!strcmp(target, "/pause")) {
300
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
301
        do_setrun(fd, 0, 1); return;
302
    }
303
    if (!strcmp(target, "/resume")) {
304
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
305
        do_setrun(fd, -1, 0); return;
306
    }
307
    send_json(fd, 404, "{\"error\":\"not found\"}");
308
}
309
310
static void *server_main(void *arg)
311
{
312
    (void)arg;
313
    for (;;) {
314
        int fd = accept(g_listen_fd, NULL, NULL);
315
        if (fd < 0) {
316
            if (errno == EINTR) continue;
317
            break;
318
        }
319
        handle_conn(fd);
320
        close(fd);
321
    }
322
    return NULL;
323
}
324
325
int retro_control_start(int port, const retro_control_backend_t *backend)
326
{
327
    g_be = backend;
328
    signal(SIGPIPE, SIG_IGN);
329
330
    int fd = socket(AF_INET, SOCK_STREAM, 0);
331
    if (fd < 0) return -1;
332
    int one = 1;
333
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
334
335
    struct sockaddr_in addr;
336
    memset(&addr, 0, sizeof addr);
337
    addr.sin_family = AF_INET;
338
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);   /* 127.0.0.1 only */
339
    addr.sin_port = htons((uint16_t)port);
340
    if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
341
        fprintf(stderr, "[retro_control] bind 127.0.0.1:%d failed: %s\n",
342
                port, strerror(errno));
343
        close(fd);
344
        return -1;
345
    }
346
    if (listen(fd, 4) < 0) { close(fd); return -1; }
347
348
    g_listen_fd = fd;
349
    if (pthread_create(&g_thread, NULL, server_main, NULL) != 0) {
350
        close(fd); g_listen_fd = -1; return -1;
351
    }
352
    pthread_detach(g_thread);
353
    fprintf(stderr, "[retro_control] listening on 127.0.0.1:%d (contract %s)\n",
354
            port, RETRO_CONTROL_CONTRACT);
355
    return 0;
356
}
357
358
void retro_control_stop(void)
359
{
360
    if (g_listen_fd >= 0) { close(g_listen_fd); g_listen_fd = -1; }
361
}
362
363
#endif /* !_WIN32 */