host_posix.c 11.2 KiB raw
1
/* POSIX implementation of the host platform layer. */
2
#ifdef __APPLE__
3
#define _DARWIN_C_SOURCE
4
#else
5
#define _DEFAULT_SOURCE
6
#endif
7
#define _POSIX_C_SOURCE 200809L
8
9
#include <dirent.h>
10
#include <errno.h>
11
#include <fcntl.h>
12
#include <signal.h>
13
#include <spawn.h>
14
#include <stdio.h>
15
#include <stdlib.h>
16
#include <string.h>
17
#include <sys/stat.h>
18
#include <sys/types.h>
19
#include <sys/wait.h>
20
#include <unistd.h>
21
22
#ifdef __APPLE__
23
#include <mach-o/dyld.h>
24
#else
25
#include <linux/fs.h>
26
#include <sys/syscall.h>
27
#endif
28
29
#include "host.h"
30
31
extern char **environ;
32
33
/* Smallest descriptor number given to internal pipes, so that they never
34
 * collide with the descriptors a child is given. */
35
#define PIPE_FD_MIN 10
36
37
/* Null device used for discarded output and empty input. */
38
#define NULL_DEVICE "/dev/null"
39
40
/* A running child: its process and the read end of its outcome pipe. */
41
struct child {
42
    bool  used;
43
    pid_t pid;
44
    int   outcome_fd;
45
};
46
47
/* Table of children that have not been waited for. */
48
static struct child children[HOST_MAX_CHILDREN];
49
50
/* Map a host errno value to a guest ABI error code. This is the only place
51
 * where host error numbers are interpreted. */
52
static i64 host_error(int err) {
53
    switch (err) {
54
    case ENOENT:
55
    case ENOTDIR:
56
        return HOST_E_NOT_FOUND;
57
    case EEXIST:
58
        return HOST_E_EXISTS;
59
    case EACCES:
60
    case EPERM:
61
    case EROFS:
62
        return HOST_E_DENIED;
63
    case ENOTEMPTY:
64
        return HOST_E_NOT_EMPTY;
65
    case EINVAL:
66
    case EBADF:
67
    case ENAMETOOLONG:
68
        return HOST_E_INVALID;
69
    case EMFILE:
70
    case ENFILE:
71
        return HOST_E_LIMIT;
72
    default:
73
        return HOST_E_IO;
74
    }
75
}
76
77
/* Return a negative error code for the current `errno`. */
78
static i64 fail(void) {
79
    return host_error(errno);
80
}
81
82
/* Open a file and make sure children do not inherit it. */
83
static i64 open_file(const char *path, int flags) {
84
    int fd = open(path, flags | O_CLOEXEC, 0644);
85
    return fd < 0 ? fail() : fd;
86
}
87
88
i64 host_open_read(const char *path) {
89
    return open_file(path, O_RDONLY);
90
}
91
92
i64 host_open_write(const char *path) {
93
    return open_file(path, O_WRONLY | O_CREAT | O_TRUNC);
94
}
95
96
i64 host_read(int fd, void *buf, u32 len) {
97
    ssize_t n;
98
    do {
99
        n = read(fd, buf, len);
100
    } while (n < 0 && errno == EINTR);
101
    return n < 0 ? fail() : n;
102
}
103
104
i64 host_write(int fd, const void *buf, u32 len) {
105
    ssize_t n;
106
    do {
107
        n = write(fd, buf, len);
108
    } while (n < 0 && errno == EINTR);
109
    return n < 0 ? fail() : n;
110
}
111
112
i64 host_close(int fd) {
113
    return close(fd) < 0 ? fail() : 0;
114
}
115
116
i64 host_stat(const char *path, struct host_stat *out) {
117
    struct stat st;
118
    if (stat(path, &st) < 0)
119
        return fail();
120
    if (S_ISREG(st.st_mode)) {
121
        out->kind = HOST_KIND_FILE;
122
        out->size = (u64)st.st_size;
123
    } else if (S_ISDIR(st.st_mode)) {
124
        out->kind = HOST_KIND_DIR;
125
        out->size = 0;
126
    } else {
127
        out->kind = HOST_KIND_OTHER;
128
        out->size = 0;
129
    }
130
    return 0;
131
}
132
133
i64 host_make_dir(const char *path) {
134
    return mkdir(path, 0755) < 0 ? fail() : 0;
135
}
136
137
i64 host_remove(const char *path) {
138
    struct stat st;
139
    if (lstat(path, &st) < 0)
140
        return fail();
141
    /* Do not follow a symbolic link to a directory: remove the link. */
142
    int rc = S_ISDIR(st.st_mode) ? rmdir(path) : unlink(path);
143
    return rc < 0 ? fail() : 0;
144
}
145
146
i64 host_rename(const char *from, const char *to) {
147
    return rename(from, to) < 0 ? fail() : 0;
148
}
149
150
i64 host_exchange(const char *left, const char *right) {
151
#ifdef __APPLE__
152
    int rc = renameatx_np(AT_FDCWD, left, AT_FDCWD, right, RENAME_SWAP);
153
#else
154
    long rc = syscall(
155
        SYS_renameat2, AT_FDCWD, left, AT_FDCWD, right, RENAME_EXCHANGE
156
    );
157
#endif
158
    return rc < 0 ? fail() : 0;
159
}
160
161
i64 host_list_dir(const char *path, u8 *buf, u32 cap) {
162
    DIR *dir = opendir(path);
163
    if (!dir)
164
        return fail();
165
166
    u64 used = 0;
167
    for (;;) {
168
        errno                  = 0;
169
        const struct dirent *e = readdir(dir);
170
        if (!e) {
171
            int err = errno;
172
            closedir(dir);
173
            return err ? host_error(err) : (i64)used;
174
        }
175
        if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
176
            continue;
177
        u64 size = (u64)strlen(e->d_name) + 1;
178
        if (size > cap - used) {
179
            closedir(dir);
180
            return HOST_E_TOO_LARGE;
181
        }
182
        memcpy(buf + used, e->d_name, size);
183
        used += size;
184
    }
185
}
186
187
/* Resolve the path of the running emulator executable into `buf`. */
188
static bool self_path(char *buf, usize cap) {
189
#ifdef __APPLE__
190
    uint32_t size = (uint32_t)cap;
191
    return _NSGetExecutablePath(buf, &size) == 0;
192
#else
193
    ssize_t n = readlink("/proc/self/exe", buf, cap - 1);
194
    if (n <= 0)
195
        return false;
196
    buf[n] = '\0';
197
    return true;
198
#endif
199
}
200
201
/* Move a descriptor to a number of at least PIPE_FD_MIN, closing the old
202
 * one. The new descriptor is close-on-exec. Returns -1 on failure. */
203
static int move_high(int fd) {
204
    int high = fcntl(fd, F_DUPFD_CLOEXEC, PIPE_FD_MIN);
205
    int err  = errno;
206
    close(fd);
207
    errno = err;
208
    return high;
209
}
210
211
/* Create the outcome pipe. Both ends are close-on-exec, so only the
212
 * child that is explicitly given the write end holds it. */
213
static bool outcome_pipe(int ends[2]) {
214
    int raw[2];
215
    if (pipe(raw) < 0)
216
        return false;
217
    ends[0] = move_high(raw[0]);
218
    if (ends[0] < 0) {
219
        close(raw[1]);
220
        return false;
221
    }
222
    ends[1] = move_high(raw[1]);
223
    if (ends[1] < 0) {
224
        close(ends[0]);
225
        return false;
226
    }
227
    return true;
228
}
229
230
/* Add the actions that connect one child output stream. */
231
static int output_actions(
232
    posix_spawn_file_actions_t *fa, int target, u32 kind, const char *path
233
) {
234
    switch (kind) {
235
    case HOST_OUT_INHERIT:
236
        return 0;
237
    case HOST_OUT_DISCARD:
238
        return posix_spawn_file_actions_addopen(
239
            fa, target, NULL_DEVICE, O_WRONLY, 0
240
        );
241
    case HOST_OUT_FILE:
242
        return posix_spawn_file_actions_addopen(
243
            fa, target, path, O_WRONLY | O_CREAT | O_TRUNC, 0644
244
        );
245
    case HOST_OUT_MERGE:
246
        return posix_spawn_file_actions_adddup2(fa, STDOUT_FILENO, target);
247
    default:
248
        return EINVAL;
249
    }
250
}
251
252
/* Build the file actions of a child. */
253
static int spawn_actions(
254
    posix_spawn_file_actions_t *fa, const struct host_spawn *spec, int out_fd
255
) {
256
    int rc = posix_spawn_file_actions_addopen(
257
        fa, STDIN_FILENO, NULL_DEVICE, O_RDONLY, 0
258
    );
259
    if (!rc)
260
        rc = posix_spawn_file_actions_adddup2(fa, out_fd, HOST_OUTCOME_FD);
261
    if (!rc)
262
        rc = output_actions(fa, STDOUT_FILENO, spec->out_kind, spec->out_path);
263
    if (!rc)
264
        rc = output_actions(fa, STDERR_FILENO, spec->err_kind, spec->err_path);
265
    return rc;
266
}
267
268
i64 host_spawn(const struct host_spawn *spec) {
269
    static char exe[HOST_PATH_MAX];
270
271
    int slot = 0;
272
    while (slot < HOST_MAX_CHILDREN && children[slot].used)
273
        slot++;
274
    if (slot == HOST_MAX_CHILDREN)
275
        return HOST_E_LIMIT;
276
    if (!exe[0] && !self_path(exe, sizeof exe))
277
        return HOST_E_IO;
278
    if (spec->out_kind == HOST_OUT_MERGE)
279
        return HOST_E_INVALID;
280
281
    /* Replace the program name in a copy of the argument vector. */
282
    usize argc = 0;
283
    while (spec->argv[argc])
284
        argc++;
285
    char **argv = malloc((argc + 1) * sizeof *argv);
286
    if (!argv)
287
        return HOST_E_IO;
288
    memcpy(argv, spec->argv, (argc + 1) * sizeof *argv);
289
    argv[0] = exe;
290
291
    int ends[2];
292
    if (!outcome_pipe(ends)) {
293
        i64 err = fail();
294
        free(argv);
295
        return err;
296
    }
297
298
    posix_spawn_file_actions_t fa;
299
    int                        rc  = posix_spawn_file_actions_init(&fa);
300
    pid_t                      pid = 0;
301
    if (!rc) {
302
        rc = spawn_actions(&fa, spec, ends[1]);
303
        if (!rc)
304
            rc = posix_spawn(&pid, exe, &fa, NULL, argv, environ);
305
        posix_spawn_file_actions_destroy(&fa);
306
    }
307
    free(argv);
308
    close(ends[1]);
309
    if (rc) {
310
        close(ends[0]);
311
        return host_error(rc);
312
    }
313
    children[slot] = (struct child){ true, pid, ends[0] };
314
    return slot;
315
}
316
317
/* Read the outcome record of an ended child and release its slot. A child
318
 * that did not leave a complete record is reported as a fault. */
319
static void collect(struct child *c, struct host_outcome *out) {
320
    u8  rec[8];
321
    u32 got = 0;
322
    while (got < sizeof rec) {
323
        ssize_t n = read(c->outcome_fd, rec + got, sizeof rec - got);
324
        if (n < 0 && errno == EINTR)
325
            continue;
326
        if (n <= 0)
327
            break;
328
        got += (u32)n;
329
    }
330
    if (got == sizeof rec) {
331
        out->kind = (u32)rec[0] | (u32)rec[1] << 8 | (u32)rec[2] << 16 |
332
                    (u32)rec[3] << 24;
333
        out->code = (i32)((u32)rec[4] | (u32)rec[5] << 8 | (u32)rec[6] << 16 |
334
                          (u32)rec[7] << 24);
335
        if (out->kind > HOST_OUTCOME_FAULT)
336
            out->kind = HOST_OUTCOME_FAULT, out->code = 0;
337
    } else {
338
        out->kind = HOST_OUTCOME_FAULT;
339
        out->code = 0;
340
    }
341
    close(c->outcome_fd);
342
    c->used = false;
343
}
344
345
/* Wait for a specific process, retrying when interrupted. */
346
static void reap(pid_t pid) {
347
    int status;
348
    while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
349
        ;
350
}
351
352
i64 host_wait(i64 child, struct host_outcome *out) {
353
    if (child < 0 || child >= HOST_MAX_CHILDREN || !children[child].used)
354
        return HOST_E_NOT_FOUND;
355
    reap(children[child].pid);
356
    collect(&children[child], out);
357
    return 0;
358
}
359
360
i64 host_wait_any(struct host_outcome *out) {
361
    bool any = false;
362
    for (int i = 0; i < HOST_MAX_CHILDREN; i++)
363
        any |= children[i].used;
364
    if (!any)
365
        return HOST_E_NOT_FOUND;
366
367
    /* The emulator starts no other processes, so any ended child is ours. */
368
    for (;;) {
369
        int   status;
370
        pid_t pid = waitpid(-1, &status, 0);
371
        if (pid < 0) {
372
            if (errno == EINTR)
373
                continue;
374
            return fail();
375
        }
376
        for (int i = 0; i < HOST_MAX_CHILDREN; i++) {
377
            if (children[i].used && children[i].pid == pid) {
378
                collect(&children[i], out);
379
                return i;
380
            }
381
        }
382
    }
383
}
384
385
/* Terminate and reap every child that has not been waited for. Only
386
 * async-signal-safe functions are used, so this runs from a handler. */
387
static void terminate_children(void) {
388
    for (int i = 0; i < HOST_MAX_CHILDREN; i++) {
389
        if (!children[i].used)
390
            continue;
391
        kill(children[i].pid, SIGTERM);
392
        reap(children[i].pid);
393
        close(children[i].outcome_fd);
394
        children[i].used = false;
395
    }
396
}
397
398
/* Terminate the children, then end the process as the signal would. */
399
static void on_terminate(int sig) {
400
    terminate_children();
401
    _exit(128 + sig);
402
}
403
404
void host_init(void) {
405
    atexit(terminate_children);
406
    signal(SIGTERM, on_terminate);
407
}
408
409
void host_report_outcome(int fd, const struct host_outcome *outcome) {
410
    u8  rec[8];
411
    u32 code = (u32)outcome->code;
412
    for (int i = 0; i < 4; i++) {
413
        rec[i]     = (u8)(outcome->kind >> (8 * i));
414
        rec[4 + i] = (u8)(code >> (8 * i));
415
    }
416
    u32 sent = 0;
417
    while (sent < sizeof rec) {
418
        ssize_t n = write(fd, rec + sent, sizeof rec - sent);
419
        if (n < 0 && errno == EINTR)
420
            continue;
421
        if (n <= 0)
422
            return;
423
        sent += (u32)n;
424
    }
425
}