OXYGENHUB
# 689a9ccb0138 retro-remote-debug-controller / core / retro_control.c
14.1 KiB · C · last changed Core: implement 0.2 input injection (POST /key, POST /reset) 3 months ago source blame history raw
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
14
#if defined(_WIN32)
15
/* No server on Windows for now — stub out so the fork still builds. */
16
int  retro_control_start(int port, const retro_control_backend_t *b) { (void)port; (void)b; return -1; }
17
void retro_control_service(void) {}
18
int  retro_control_running(void) { return 1; }
19
void retro_control_on_frame(void) {}
20
void retro_control_stop(void) {}
21
#else
22
23
#include <pthread.h>
24
#include <unistd.h>
25
#include <errno.h>
26
#include <signal.h>
27
#include <sys/socket.h>
28
#include <netinet/in.h>
29
#include <arpa/inet.h>
30
31
#ifndef MSG_NOSIGNAL
32
#define MSG_NOSIGNAL 0
33
#endif
34
35
#define MEM_CAP (1u << 20)   /* /mem hard cap: 1 MiB per request */
36
37
static const retro_control_backend_t *g_be = NULL;
38
static int       g_listen_fd = -1;
39
static pthread_t g_thread;
40
41
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
42
static pthread_cond_t  g_cv   = PTHREAD_COND_INITIALIZER;
43
44
/* run control: -1 free-run, 0 halted, >0 run this many frames then halt */
45
static long g_frames_to_run = -1;
46
static int  g_step_waiting  = 0;
47
48
/* single-slot marshalled request (mem / regs / screenshot / key / reset) */
49
typedef enum { REQ_NONE = 0, REQ_MEM, REQ_REGS, REQ_SHOT, REQ_KEY, REQ_RESET } req_t;
50
static volatile req_t g_req = REQ_NONE;
51
static uint32_t g_req_addr, g_req_len;
52
static int32_t  g_req_bank;
53
static int      g_key_is_text;   /* 1 => g_key_value is a char code point */
54
static uint32_t g_key_value;
55
static int      g_key_action;    /* retro_key_action_t */
56
57
static uint8_t    *g_resp_body  = NULL;
58
static size_t      g_resp_len   = 0;
59
static int         g_resp_status = 200;
60
static const char *g_resp_ctype = "application/octet-stream";
61
static int         g_resp_ready = 0;
62
63
/* ---- emulator-thread side ------------------------------------------------ */
64
65
static void build_ppm(void)
66
{
67
    retro_framebuffer_t fb;
68
    memset(&fb, 0, sizeof fb);
69
    g_be->get_framebuffer(&fb);
70
    int w = fb.width, h = fb.height;
71
    int bpp = (fb.fmt == RETRO_PIX_RGB888) ? 3 : 4;
72
73
    char hdr[64];
74
    int hl = snprintf(hdr, sizeof hdr, "P6\n%d %d\n255\n", w, h);
75
    size_t total = (size_t)hl + (size_t)3 * w * h;
76
    uint8_t *out = (uint8_t *)malloc(total ? total : 1);
77
    if (!out) { g_resp_body = NULL; g_resp_len = 0; g_resp_status = 500; return; }
78
79
    memcpy(out, hdr, hl);
80
    uint8_t *p = out + hl;
81
    const uint8_t *s = fb.pixels;
82
    for (int i = 0; i < w * h; i++) {
83
        const uint8_t *px = s + (size_t)i * bpp;
84
        if (fb.fmt == RETRO_PIX_BGRA8888) {
85
            p[0] = px[2]; p[1] = px[1]; p[2] = px[0];
86
        } else {                       /* RGB888 / RGBA8888 */
87
            p[0] = px[0]; p[1] = px[1]; p[2] = px[2];
88
        }
89
        p += 3;
90
    }
91
    g_resp_body = out;
92
    g_resp_len = total;
93
    g_resp_status = 200;
94
    g_resp_ctype = "image/x-portable-pixmap";
95
}
96
97
void retro_control_service(void)
98
{
99
    if (!g_be || g_req == REQ_NONE) return;   /* cheap unlocked fast-path */
100
101
    pthread_mutex_lock(&g_lock);
102
    switch (g_req) {
103
    case REQ_MEM: {
104
        uint32_t len = g_req_len > MEM_CAP ? MEM_CAP : g_req_len;
105
        uint8_t *buf = (uint8_t *)malloc(len ? len : 1);
106
        uint32_t got = 0;
107
        if (buf && g_be->read_mem) got = g_be->read_mem(g_req_addr, g_req_bank, len, buf, len);
108
        g_resp_body = buf; g_resp_len = got;
109
        g_resp_status = g_be->read_mem ? 200 : 501;
110
        g_resp_ctype = "application/octet-stream";
111
        break;
112
    }
113
    case REQ_REGS: {
114
        char *buf = (char *)malloc(1024);
115
        if (buf && g_be->get_regs_json) { g_be->get_regs_json(buf, 1024); }
116
        else if (buf) { buf[0] = 0; }
117
        g_resp_body = (uint8_t *)buf; g_resp_len = buf ? strlen(buf) : 0;
118
        g_resp_status = g_be->get_regs_json ? 200 : 501;
119
        g_resp_ctype = "application/json";
120
        break;
121
    }
122
    case REQ_SHOT:
123
        if (g_be->get_framebuffer) build_ppm();
124
        else { g_resp_body = NULL; g_resp_len = 0; g_resp_status = 501; }
125
        break;
126
    case REQ_KEY: {
127
        const char *json;
128
        if (!g_be->inject_key) {
129
            json = "{\"error\":\"not implemented\"}"; g_resp_status = 501;
130
        } else if (g_be->inject_key(g_key_is_text, g_key_value, g_key_action)) {
131
            json = "{\"injected\":true}"; g_resp_status = 200;
132
        } else {
133
            json = "{\"error\":\"unmapped key\"}"; g_resp_status = 400;
134
        }
135
        size_t l = strlen(json);
136
        uint8_t *b = (uint8_t *)malloc(l + 1);
137
        if (b) memcpy(b, json, l + 1);
138
        g_resp_body = b; g_resp_len = b ? l : 0;
139
        g_resp_ctype = "application/json";
140
        break;
141
    }
142
    case REQ_RESET: {
143
        const char *json;
144
        if (g_be->reset) { g_be->reset(); json = "{\"reset\":true}"; g_resp_status = 200; }
145
        else { json = "{\"error\":\"not implemented\"}"; g_resp_status = 501; }
146
        size_t l = strlen(json);
147
        uint8_t *b = (uint8_t *)malloc(l + 1);
148
        if (b) memcpy(b, json, l + 1);
149
        g_resp_body = b; g_resp_len = b ? l : 0;
150
        g_resp_ctype = "application/json";
151
        break;
152
    }
153
    default: break;
154
    }
155
    g_req = REQ_NONE;
156
    g_resp_ready = 1;
157
    pthread_cond_broadcast(&g_cv);
158
    pthread_mutex_unlock(&g_lock);
159
}
160
161
int retro_control_running(void)
162
{
163
    if (!g_be) return 1;
164
    pthread_mutex_lock(&g_lock);
165
    long f = g_frames_to_run;
166
    pthread_mutex_unlock(&g_lock);
167
    return f != 0;
168
}
169
170
void retro_control_on_frame(void)
171
{
172
    if (!g_be) return;
173
    pthread_mutex_lock(&g_lock);
174
    if (g_frames_to_run > 0) {
175
        g_frames_to_run--;
176
        if (g_frames_to_run == 0 && g_step_waiting) {
177
            g_step_waiting = 0;
178
            g_resp_ready = 1;
179
            pthread_cond_broadcast(&g_cv);
180
        }
181
    }
182
    pthread_mutex_unlock(&g_lock);
183
}
184
185
/* ---- server-thread side -------------------------------------------------- */
186
187
static void write_all(int fd, const void *buf, size_t len)
188
{
189
    const char *p = (const char *)buf;
190
    while (len) {
191
        ssize_t w = send(fd, p, len, MSG_NOSIGNAL);
192
        if (w <= 0) return;
193
        p += w; len -= (size_t)w;
194
    }
195
}
196
197
static void send_http(int fd, int status, const char *ctype,
198
                      const uint8_t *body, size_t len)
199
{
200
    const char *reason =
201
        status == 200 ? "OK" :
202
        status == 400 ? "Bad Request" :
203
        status == 404 ? "Not Found" :
204
        status == 405 ? "Method Not Allowed" :
205
        status == 501 ? "Not Implemented" : "Error";
206
    char hdr[256];
207
    int hl = snprintf(hdr, sizeof hdr,
208
        "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\n"
209
        "Connection: close\r\nAccess-Control-Allow-Origin: *\r\n\r\n",
210
        status, reason, ctype, len);
211
    write_all(fd, hdr, hl);
212
    if (body && len) write_all(fd, body, len);
213
}
214
215
static void send_json(int fd, int status, const char *json)
216
{
217
    send_http(fd, status, "application/json", (const uint8_t *)json, strlen(json));
218
}
219
220
/* value of query key, decimal or 0x-hex (strtol base 0); def if absent. */
221
static long query_long(const char *q, const char *key, long def)
222
{
223
    size_t kl = strlen(key);
224
    const char *p = q;
225
    while (p && *p) {
226
        if (!strncmp(p, key, kl) && p[kl] == '=')
227
            return strtol(p + kl + 1, NULL, 0);
228
        p = strchr(p, '&');
229
        if (p) p++;
230
    }
231
    return def;
232
}
233
234
/* copy the value of query key into out (NUL-terminated, truncated to cap).
235
 * Returns 1 if the key was present, 0 otherwise. */
236
static int query_str(const char *q, const char *key, char *out, size_t cap)
237
{
238
    size_t kl = strlen(key);
239
    const char *p = q;
240
    while (p && *p) {
241
        if (!strncmp(p, key, kl) && p[kl] == '=') {
242
            const char *v = p + kl + 1;
243
            const char *e = strchr(v, '&');
244
            size_t n = e ? (size_t)(e - v) : strlen(v);
245
            if (n >= cap) n = cap - 1;
246
            memcpy(out, v, n);
247
            out[n] = 0;
248
            return 1;
249
        }
250
        p = strchr(p, '&');
251
        if (p) p++;
252
    }
253
    if (cap) out[0] = 0;
254
    return 0;
255
}
256
257
/* marshal a read to the emulator thread, wait, send the response. */
258
static void do_marshalled(int fd, req_t r)
259
{
260
    pthread_mutex_lock(&g_lock);
261
    g_resp_ready = 0; g_resp_body = NULL; g_resp_len = 0;
262
    g_req = r;
263
    while (!g_resp_ready) pthread_cond_wait(&g_cv, &g_lock);
264
    uint8_t *body = g_resp_body; size_t len = g_resp_len;
265
    int st = g_resp_status; const char *ct = g_resp_ctype;
266
    g_resp_body = NULL;
267
    pthread_mutex_unlock(&g_lock);
268
269
    send_http(fd, st, ct, body, len);
270
    free(body);
271
}
272
273
static void do_status(int fd)
274
{
275
    pthread_mutex_lock(&g_lock);
276
    long f = g_frames_to_run;
277
    pthread_mutex_unlock(&g_lock);
278
    unsigned long long fc = g_be->get_frame_count ? g_be->get_frame_count() : 0;
279
    /* Advertise 0.2 only when the backend actually offers input injection. */
280
    const char *contract = g_be->inject_key ? "0.2.0" : "0.1.0";
281
    char buf[320];
282
    snprintf(buf, sizeof buf,
283
        "{\"contract\":\"%s\",\"emulator\":\"%s\",\"platform\":\"%s\","
284
        "\"frame\":%llu,\"paused\":%s,\"running\":true}",
285
        contract,
286
        g_be->emulator ? g_be->emulator : "",
287
        g_be->platform ? g_be->platform : "",
288
        fc, (f == 0) ? "true" : "false");
289
    send_json(fd, 200, buf);
290
}
291
292
static void do_step(int fd, const char *query)
293
{
294
    long n = query_long(query, "frames", 1);
295
    if (n < 1) n = 1;
296
    pthread_mutex_lock(&g_lock);
297
    g_frames_to_run = n;
298
    g_step_waiting = 1;
299
    g_resp_ready = 0;
300
    while (!g_resp_ready) pthread_cond_wait(&g_cv, &g_lock);
301
    pthread_mutex_unlock(&g_lock);
302
303
    unsigned long long fc = g_be->get_frame_count ? g_be->get_frame_count() : 0;
304
    char buf[64];
305
    snprintf(buf, sizeof buf, "{\"frame\":%llu}", fc);
306
    send_json(fd, 200, buf);
307
}
308
309
static void do_setrun(int fd, long v, int paused)
310
{
311
    pthread_mutex_lock(&g_lock);
312
    g_frames_to_run = v;
313
    pthread_mutex_unlock(&g_lock);
314
    send_json(fd, 200, paused ? "{\"paused\":true}" : "{\"paused\":false}");
315
}
316
317
static void handle_conn(int fd)
318
{
319
    char req[2048];
320
    size_t n = 0;
321
    while (n < sizeof(req) - 1) {
322
        ssize_t r = recv(fd, req + n, sizeof(req) - 1 - n, 0);
323
        if (r <= 0) break;
324
        n += (size_t)r;
325
        if (strstr(req, "\r\n\r\n")) break;
326
    }
327
    req[n] = 0;
328
329
    char method[8] = {0}, target[1024] = {0};
330
    if (sscanf(req, "%7s %1023s", method, target) != 2) {
331
        send_json(fd, 400, "{\"error\":\"bad request\"}");
332
        return;
333
    }
334
    char *q = strchr(target, '?');
335
    const char *query = "";
336
    if (q) { *q = 0; query = q + 1; }
337
    int is_post = !strcmp(method, "POST");
338
339
    if (!strcmp(target, "/status"))          { do_status(fd); return; }
340
    if (!strcmp(target, "/regs"))            { do_marshalled(fd, REQ_REGS); return; }
341
    if (!strcmp(target, "/screenshot"))      { do_marshalled(fd, REQ_SHOT); return; }
342
    if (!strcmp(target, "/mem")) {
343
        g_req_addr = (uint32_t)query_long(query, "addr", 0);
344
        g_req_len  = (uint32_t)query_long(query, "len", 0);
345
        g_req_bank = (int32_t)query_long(query, "bank", -1);
346
        do_marshalled(fd, REQ_MEM);
347
        return;
348
    }
349
    if (!strcmp(target, "/step")) {
350
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
351
        do_step(fd, query); return;
352
    }
353
    if (!strcmp(target, "/pause")) {
354
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
355
        do_setrun(fd, 0, 1); return;
356
    }
357
    if (!strcmp(target, "/resume")) {
358
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
359
        do_setrun(fd, -1, 0); return;
360
    }
361
    if (!strcmp(target, "/key")) {
362
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
363
        char text[8];
364
        long code = query_long(query, "code", -1);
365
        long down = query_long(query, "down", -1);
366
        if (query_str(query, "text", text, sizeof text) && text[0]) {
367
            g_key_is_text = 1; g_key_value = (uint32_t)(unsigned char)text[0];
368
        } else if (code >= 0) {
369
            g_key_is_text = 0; g_key_value = (uint32_t)code;
370
        } else {
371
            send_json(fd, 400, "{\"error\":\"key needs text= or code=\"}"); return;
372
        }
373
        g_key_action = (down < 0) ? RETRO_KEY_TAP
374
                     : (down != 0) ? RETRO_KEY_DOWN : RETRO_KEY_UP;
375
        do_marshalled(fd, REQ_KEY);
376
        return;
377
    }
378
    if (!strcmp(target, "/reset")) {
379
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
380
        do_marshalled(fd, REQ_RESET);
381
        return;
382
    }
383
    send_json(fd, 404, "{\"error\":\"not found\"}");
384
}
385
386
static void *server_main(void *arg)
387
{
388
    (void)arg;
389
    for (;;) {
390
        int fd = accept(g_listen_fd, NULL, NULL);
391
        if (fd < 0) {
392
            if (errno == EINTR) continue;
393
            break;
394
        }
395
        handle_conn(fd);
396
        close(fd);
397
    }
398
    return NULL;
399
}
400
401
int retro_control_start(int port, const retro_control_backend_t *backend)
402
{
403
    g_be = backend;
404
    signal(SIGPIPE, SIG_IGN);
405
406
    int fd = socket(AF_INET, SOCK_STREAM, 0);
407
    if (fd < 0) return -1;
408
    int one = 1;
409
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
410
411
    struct sockaddr_in addr;
412
    memset(&addr, 0, sizeof addr);
413
    addr.sin_family = AF_INET;
414
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);   /* 127.0.0.1 only */
415
    addr.sin_port = htons((uint16_t)port);
416
    if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
417
        fprintf(stderr, "[retro_control] bind 127.0.0.1:%d failed: %s\n",
418
                port, strerror(errno));
419
        close(fd);
420
        return -1;
421
    }
422
    if (listen(fd, 4) < 0) { close(fd); return -1; }
423
424
    g_listen_fd = fd;
425
    if (pthread_create(&g_thread, NULL, server_main, NULL) != 0) {
426
        close(fd); g_listen_fd = -1; return -1;
427
    }
428
    pthread_detach(g_thread);
429
    fprintf(stderr, "[retro_control] listening on 127.0.0.1:%d (contract %s)\n",
430
            port, RETRO_CONTROL_CONTRACT);
431
    return 0;
432
}
433
434
void retro_control_stop(void)
435
{
436
    if (g_listen_fd >= 0) { close(g_listen_fd); g_listen_fd = -1; }
437
}
438
439
#endif /* !_WIN32 */