gdb-server/main.c

155 lines
3.6 KiB
C

#include <client.h>
#include <cmdbuf.h>
#include <request.h>
#include <server.h>
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <vb.h>
const size_t BUFLEN = 8096;
int server(int connfd, VB *sim) {
RdbRequest req;
RdbClient client;
char buf[BUFLEN];
rdb_request_init(&req, connfd, buf, BUFLEN);
rdb_client_init(&client, connfd);
bool running = false;
while (1) {
CommandBuf cmd;
rdb_read_result_t result = rdb_request_read(&req, &cmd);
if (result == read_result_error) {
return -1;
} else if (result == read_result_disconnected) {
printf("client has disconnected\n");
return 0;
} else if (result == read_result_pending) {
if (running) {
printf("pretend the emulator is running now\n");
sleep(1);
}
continue;
} else {
printf("received command \"%.*s\"\n", (int) cmd.len, cmd.buf);
fflush(stdout);
int res = handle_command(&client, &cmd, sim, &running);
if (res != 0) {
return res;
}
rdb_request_set_blocking(&req, !running);
rdb_request_reset(&req);
}
}
}
int readROM(VB *sim, char *filename) {
FILE *file = fopen(filename, "rb");
long size;
if (!file) {
perror("could not open file");
return 1;
}
if (fseek(file, 0, SEEK_END)) {
perror("could not seek file end");
return 1;
}
size = ftell(file);
if (size == -1) {
perror("could not read file size");
return 1;
}
if (fseek(file, 0, SEEK_SET)) {
perror("could not seek file start");
return 1;
}
uint8_t *rom = malloc(size);
if (!rom) {
perror("could not allocate ROM");
return 1;
}
fread(rom, 1, size, file);
if (ferror(file)) {
perror("could not read file");
return 1;
}
if (fclose(file)) {
perror("could not close file");
return 1;
}
vbSetCartROM(sim, rom, size);
return 0;
}
int main(int argc, char** argv) {
if (argc < 2) {
fprintf(stderr, "Please pass a ROM file\n");
return 1;
}
VB *sim = malloc(vbSizeOf());
if (!sim) {
return 1;
}
vbInit(sim);
if (readROM(sim, argv[1])) {
return 1;
}
vbSetProgramCounter(sim, 0x07000000);
short port;
if (argc > 2) {
char *end;
port = (short) strtol(argv[2], &end, 10);
if (argv[2] == end) {
perror("could not parse port");
return 1;
}
} else {
port = 8080;
}
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1) {
perror("could not open socket");
return 1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
perror("could not bind socket");
return 1;
}
if (listen(fd, 1) == -1) {
perror("could not listen on socket");
return 1;
}
printf("connecting\n");
int connfd;
struct sockaddr_in cliaddr;
socklen_t cliaddrlen = sizeof(cliaddr);
connfd = accept(fd, (struct sockaddr *) &cliaddr, &cliaddrlen);
if (connfd == -1) {
perror("could not accept connection");
return 1;
}
printf("connected\n");
int response = server(connfd, sim);
return close(connfd)
|| close(fd)
|| response;
}