/* POSIX implementation of the host platform layer. */ #ifdef __APPLE__ #define _DARWIN_C_SOURCE #else #define _DEFAULT_SOURCE #endif #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include #include #include #include #include #include #ifdef __APPLE__ #include #else #include #include #endif #include "host.h" extern char **environ; /* Smallest descriptor number given to internal pipes, so that they never * collide with the descriptors a child is given. */ #define PIPE_FD_MIN 10 /* Null device used for discarded output and empty input. */ #define NULL_DEVICE "/dev/null" /* A running child: its process and the read end of its outcome pipe. */ struct child { bool used; pid_t pid; int outcome_fd; }; /* Table of children that have not been waited for. */ static struct child children[HOST_MAX_CHILDREN]; /* Map a host errno value to a guest ABI error code. This is the only place * where host error numbers are interpreted. */ static i64 host_error(int err) { switch (err) { case ENOENT: case ENOTDIR: return HOST_E_NOT_FOUND; case EEXIST: return HOST_E_EXISTS; case EACCES: case EPERM: case EROFS: return HOST_E_DENIED; case ENOTEMPTY: return HOST_E_NOT_EMPTY; case EINVAL: case EBADF: case ENAMETOOLONG: return HOST_E_INVALID; case EMFILE: case ENFILE: return HOST_E_LIMIT; default: return HOST_E_IO; } } /* Return a negative error code for the current `errno`. */ static i64 fail(void) { return host_error(errno); } /* Open a file and make sure children do not inherit it. */ static i64 open_file(const char *path, int flags) { int fd = open(path, flags | O_CLOEXEC, 0644); return fd < 0 ? fail() : fd; } i64 host_open_read(const char *path) { return open_file(path, O_RDONLY); } i64 host_open_write(const char *path) { return open_file(path, O_WRONLY | O_CREAT | O_TRUNC); } i64 host_read(int fd, void *buf, u32 len) { ssize_t n; do { n = read(fd, buf, len); } while (n < 0 && errno == EINTR); return n < 0 ? fail() : n; } i64 host_write(int fd, const void *buf, u32 len) { ssize_t n; do { n = write(fd, buf, len); } while (n < 0 && errno == EINTR); return n < 0 ? fail() : n; } i64 host_close(int fd) { return close(fd) < 0 ? fail() : 0; } i64 host_stat(const char *path, struct host_stat *out) { struct stat st; if (stat(path, &st) < 0) return fail(); if (S_ISREG(st.st_mode)) { out->kind = HOST_KIND_FILE; out->size = (u64)st.st_size; } else if (S_ISDIR(st.st_mode)) { out->kind = HOST_KIND_DIR; out->size = 0; } else { out->kind = HOST_KIND_OTHER; out->size = 0; } return 0; } i64 host_make_dir(const char *path) { return mkdir(path, 0755) < 0 ? fail() : 0; } i64 host_remove(const char *path) { struct stat st; if (lstat(path, &st) < 0) return fail(); /* Do not follow a symbolic link to a directory: remove the link. */ int rc = S_ISDIR(st.st_mode) ? rmdir(path) : unlink(path); return rc < 0 ? fail() : 0; } i64 host_rename(const char *from, const char *to) { return rename(from, to) < 0 ? fail() : 0; } i64 host_exchange(const char *left, const char *right) { #ifdef __APPLE__ int rc = renameatx_np(AT_FDCWD, left, AT_FDCWD, right, RENAME_SWAP); #else long rc = syscall( SYS_renameat2, AT_FDCWD, left, AT_FDCWD, right, RENAME_EXCHANGE ); #endif return rc < 0 ? fail() : 0; } i64 host_list_dir(const char *path, u8 *buf, u32 cap) { DIR *dir = opendir(path); if (!dir) return fail(); u64 used = 0; for (;;) { errno = 0; const struct dirent *e = readdir(dir); if (!e) { int err = errno; closedir(dir); return err ? host_error(err) : (i64)used; } if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue; u64 size = (u64)strlen(e->d_name) + 1; if (size > cap - used) { closedir(dir); return HOST_E_TOO_LARGE; } memcpy(buf + used, e->d_name, size); used += size; } } /* Resolve the path of the running emulator executable into `buf`. */ static bool self_path(char *buf, usize cap) { #ifdef __APPLE__ uint32_t size = (uint32_t)cap; return _NSGetExecutablePath(buf, &size) == 0; #else ssize_t n = readlink("/proc/self/exe", buf, cap - 1); if (n <= 0) return false; buf[n] = '\0'; return true; #endif } /* Move a descriptor to a number of at least PIPE_FD_MIN, closing the old * one. The new descriptor is close-on-exec. Returns -1 on failure. */ static int move_high(int fd) { int high = fcntl(fd, F_DUPFD_CLOEXEC, PIPE_FD_MIN); int err = errno; close(fd); errno = err; return high; } /* Create the outcome pipe. Both ends are close-on-exec, so only the * child that is explicitly given the write end holds it. */ static bool outcome_pipe(int ends[2]) { int raw[2]; if (pipe(raw) < 0) return false; ends[0] = move_high(raw[0]); if (ends[0] < 0) { close(raw[1]); return false; } ends[1] = move_high(raw[1]); if (ends[1] < 0) { close(ends[0]); return false; } return true; } /* Add the actions that connect one child output stream. */ static int output_actions( posix_spawn_file_actions_t *fa, int target, u32 kind, const char *path ) { switch (kind) { case HOST_OUT_INHERIT: return 0; case HOST_OUT_DISCARD: return posix_spawn_file_actions_addopen( fa, target, NULL_DEVICE, O_WRONLY, 0 ); case HOST_OUT_FILE: return posix_spawn_file_actions_addopen( fa, target, path, O_WRONLY | O_CREAT | O_TRUNC, 0644 ); case HOST_OUT_MERGE: return posix_spawn_file_actions_adddup2(fa, STDOUT_FILENO, target); default: return EINVAL; } } /* Build the file actions of a child. */ static int spawn_actions( posix_spawn_file_actions_t *fa, const struct host_spawn *spec, int out_fd ) { int rc = posix_spawn_file_actions_addopen( fa, STDIN_FILENO, NULL_DEVICE, O_RDONLY, 0 ); if (!rc) rc = posix_spawn_file_actions_adddup2(fa, out_fd, HOST_OUTCOME_FD); if (!rc) rc = output_actions(fa, STDOUT_FILENO, spec->out_kind, spec->out_path); if (!rc) rc = output_actions(fa, STDERR_FILENO, spec->err_kind, spec->err_path); return rc; } i64 host_spawn(const struct host_spawn *spec) { static char exe[HOST_PATH_MAX]; int slot = 0; while (slot < HOST_MAX_CHILDREN && children[slot].used) slot++; if (slot == HOST_MAX_CHILDREN) return HOST_E_LIMIT; if (!exe[0] && !self_path(exe, sizeof exe)) return HOST_E_IO; if (spec->out_kind == HOST_OUT_MERGE) return HOST_E_INVALID; /* Replace the program name in a copy of the argument vector. */ usize argc = 0; while (spec->argv[argc]) argc++; char **argv = malloc((argc + 1) * sizeof *argv); if (!argv) return HOST_E_IO; memcpy(argv, spec->argv, (argc + 1) * sizeof *argv); argv[0] = exe; int ends[2]; if (!outcome_pipe(ends)) { i64 err = fail(); free(argv); return err; } posix_spawn_file_actions_t fa; int rc = posix_spawn_file_actions_init(&fa); pid_t pid = 0; if (!rc) { rc = spawn_actions(&fa, spec, ends[1]); if (!rc) rc = posix_spawn(&pid, exe, &fa, NULL, argv, environ); posix_spawn_file_actions_destroy(&fa); } free(argv); close(ends[1]); if (rc) { close(ends[0]); return host_error(rc); } children[slot] = (struct child){ true, pid, ends[0] }; return slot; } /* Read the outcome record of an ended child and release its slot. A child * that did not leave a complete record is reported as a fault. */ static void collect(struct child *c, struct host_outcome *out) { u8 rec[8]; u32 got = 0; while (got < sizeof rec) { ssize_t n = read(c->outcome_fd, rec + got, sizeof rec - got); if (n < 0 && errno == EINTR) continue; if (n <= 0) break; got += (u32)n; } if (got == sizeof rec) { out->kind = (u32)rec[0] | (u32)rec[1] << 8 | (u32)rec[2] << 16 | (u32)rec[3] << 24; out->code = (i32)((u32)rec[4] | (u32)rec[5] << 8 | (u32)rec[6] << 16 | (u32)rec[7] << 24); if (out->kind > HOST_OUTCOME_FAULT) out->kind = HOST_OUTCOME_FAULT, out->code = 0; } else { out->kind = HOST_OUTCOME_FAULT; out->code = 0; } close(c->outcome_fd); c->used = false; } /* Wait for a specific process, retrying when interrupted. */ static void reap(pid_t pid) { int status; while (waitpid(pid, &status, 0) < 0 && errno == EINTR) ; } i64 host_wait(i64 child, struct host_outcome *out) { if (child < 0 || child >= HOST_MAX_CHILDREN || !children[child].used) return HOST_E_NOT_FOUND; reap(children[child].pid); collect(&children[child], out); return 0; } i64 host_wait_any(struct host_outcome *out) { bool any = false; for (int i = 0; i < HOST_MAX_CHILDREN; i++) any |= children[i].used; if (!any) return HOST_E_NOT_FOUND; /* The emulator starts no other processes, so any ended child is ours. */ for (;;) { int status; pid_t pid = waitpid(-1, &status, 0); if (pid < 0) { if (errno == EINTR) continue; return fail(); } for (int i = 0; i < HOST_MAX_CHILDREN; i++) { if (children[i].used && children[i].pid == pid) { collect(&children[i], out); return i; } } } } /* Terminate and reap every child that has not been waited for. Only * async-signal-safe functions are used, so this runs from a handler. */ static void terminate_children(void) { for (int i = 0; i < HOST_MAX_CHILDREN; i++) { if (!children[i].used) continue; kill(children[i].pid, SIGTERM); reap(children[i].pid); close(children[i].outcome_fd); children[i].used = false; } } /* Terminate the children, then end the process as the signal would. */ static void on_terminate(int sig) { terminate_children(); _exit(128 + sig); } void host_init(void) { atexit(terminate_children); signal(SIGTERM, on_terminate); } void host_report_outcome(int fd, const struct host_outcome *outcome) { u8 rec[8]; u32 code = (u32)outcome->code; for (int i = 0; i < 4; i++) { rec[i] = (u8)(outcome->kind >> (8 * i)); rec[4 + i] = (u8)(code >> (8 * i)); } u32 sent = 0; while (sent < sizeof rec) { ssize_t n = write(fd, rec + sent, sizeof rec - sent); if (n < 0 && errno == EINTR) continue; if (n <= 0) return; sent += (u32)n; } }