Artifact dd9a3be5b734fef8a715b4ceed8fb4466182ed6e194561b4189b55622a37179d:
- File
src/tools.c
— part of check-in
[e0a4799a8b]
at
2026-11-18 20:59:26
on branch stage-3
— Benchmark every tool and stop bash waiting 50ms for each exit
make bench-pic measures each tool alone, one journal commit, a scripted turn per tool and process start-up, and compares medians with a per-platform baseline, failing only when a regression repeats on three runs. The first run showed bash true at 60ms because the supervisor slept 50ms between exit checks; it now starts at 1ms and backs off, bringing it to 9ms. (user: dmestas, size: 34448) [annotate] [blame] [check-ins using] [more...]
/* Tools: Pi's default set (read, write, edit, bash) with Pi's inputs, limits * and messages. Each runs outside any database transaction and returns a * malloc'd result with *is_error set. hooks->started() commits that the effect * has begun; it is called exactly once, before any external effect, and a * nonzero return means nothing ran (the tool then returns NULL). * * read, write and edit are replay-safe: write's bytes come from its input, * and edit computes the new file content first and journals it as the plan * when it commits "started", so a replay writes the same bytes. bash is not. */ #include <errno.h> #include <fcntl.h> #include <poll.h> #include <signal.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "pic.h" #define MAX_LINES 2000 #define MAX_BYTES 51200 #define READ_FILE_CAP (256u << 20) static char *format(const char *fmt, ...) { va_list ap; char *out; int n; va_start(ap, fmt); n = vsnprintf(NULL, 0, fmt, ap); va_end(ap); if (n < 0 || !(out = malloc((size_t)n + 1))) { return NULL; } va_start(ap, fmt); (void)vsnprintf(out, (size_t)n + 1, fmt, ap); va_end(ap); return out; } /* An error result: is_error set, text formatted. */ static char *fail(int *is_error, const char *fmt, ...) { va_list ap; char *out; int n; *is_error = 1; va_start(ap, fmt); n = vsnprintf(NULL, 0, fmt, ap); va_end(ap); if (n < 0 || !(out = malloc((size_t)n + 1))) { return NULL; } va_start(ap, fmt); (void)vsnprintf(out, (size_t)n + 1, fmt, ap); va_end(ap); return out; } int pic_tool_replay_safe(const char *tool) { return strcmp(tool, "read") == 0 || strcmp(tool, "write") == 0 || strcmp(tool, "edit") == 0; } const char pic_tool_schemas[] = "[{\"name\":\"read\",\"description\":\"Read the contents of a file. For text files, output is truncated to 2000 " "lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue " "with offset until complete.\",\"input_schema\":{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\",\"description\":\"Path to the file to read (relative or absolute)\"}," "\"offset\":{\"type\":\"number\",\"description\":\"Line number to start reading from (1-indexed)\"}," "\"limit\":{\"type\":\"number\",\"description\":\"Maximum number of lines to read\"}},\"required\":[\"path\"]}}," "{\"name\":\"bash\",\"description\":\"Execute a bash command in the current working directory. Returns stdout and " "stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is " "saved to a temp file. Optionally provide a timeout in seconds.\",\"input_schema\":{\"type\":\"object\"," "\"properties\":{\"command\":{\"type\":\"string\",\"description\":\"Bash command to execute\"}," "\"timeout\":{\"type\":\"number\",\"description\":\"Timeout in seconds (optional)\"}},\"required\":[\"command\"]}}," "{\"name\":\"edit\",\"description\":\"Edit a single file using exact text replacement. Every edits[].oldText must " "match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby " "lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions " "just to connect distant changes.\",\"input_schema\":{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\",\"description\":\"Path to the file to edit (relative or absolute)\"}," "\"edits\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{" "\"oldText\":{\"type\":\"string\",\"description\":\"Exact text to find; must be unique in the original file\"}," "\"newText\":{\"type\":\"string\",\"description\":\"Replacement text\"}},\"required\":[\"oldText\",\"newText\"]}}}," "\"required\":[\"path\",\"edits\"]}}," "{\"name\":\"write\",\"description\":\"Write content to a file. Creates the file if it doesn't exist, overwrites " "if it does. Automatically creates parent directories.\",\"input_schema\":{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\",\"description\":\"Path to the file to write (relative or absolute)\"}," "\"content\":{\"type\":\"string\",\"description\":\"Content to write to the file\"}}," "\"required\":[\"path\",\"content\"]}}]"; /* ---- files ------------------------------------------------------------------ */ /* Durable on macOS too: plain fsync there does not flush the drive cache. */ static int durable_sync(int fd) { #ifdef F_FULLFSYNC if (fcntl(fd, F_FULLFSYNC) == 0) { return 0; } #endif return fsync(fd); } static int write_all(int fd, const char *p, size_t n) { while (n > 0) { ssize_t w = write(fd, p, n); if (w < 0) { if (errno == EINTR) { continue; } return -1; } p += w; n -= (size_t)w; } return 0; } /* Pi's path rules: a leading '@' is dropped, '~' is the home directory, * absolute paths are used as given and relative ones are under the * workspace. There is no sandbox. */ static char *resolve(const char *workspace, const char *path) { const char *home = getenv("HOME"); if (path[0] == '@') { path++; } if (home && (strcmp(path, "~") == 0 || strncmp(path, "~/", 2) == 0)) { return format("%s%s", home, path + 1); } if (path[0] == '/') { return format("%s", path); } return format("%s/%s", workspace, path); } static void sync_dir_of(const char *path) { char *dir = format("%s", path), *slash; int fd; if (!dir) { return; } slash = strrchr(dir, '/'); if (slash == dir) { slash[1] = '\0'; } else if (slash) { *slash = '\0'; } fd = open(slash ? dir : ".", O_RDONLY | O_CLOEXEC); if (fd >= 0) { (void)durable_sync(fd); close(fd); } free(dir); } /* mkdir -p for path's parent; each new directory's entry is made durable. */ static int make_parents(const char *path) { char *p = format("%s", path); int rc = 0; if (!p) { return -1; } for (char *s = strchr(p + 1, '/'); s && rc == 0; s = strchr(s + 1, '/')) { *s = '\0'; if (mkdir(p, 0755) == 0) { sync_dir_of(p); } else if (errno != EEXIST) { rc = -1; } *s = '/'; } free(p); return rc; } /* Replaces path with bytes atomically and durably: temp file, sync, rename, * then sync the directory so the rename survives power loss. */ static int replace_file(const char *path, const char *bytes, size_t len, mode_t mode) { char *tmp = format("%s.pic-tmp", path); int fd, e; if (!tmp) { return ENOMEM; } fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, mode); if (fd < 0) { e = errno; free(tmp); return e; } if (write_all(fd, bytes, len) != 0 || durable_sync(fd) != 0) { e = errno; close(fd); unlink(tmp); free(tmp); return e; } close(fd); if (rename(tmp, path) != 0) { e = errno; unlink(tmp); free(tmp); return e; } free(tmp); sync_dir_of(path); return 0; } /* Reads a whole regular file. NULL with *err set to an errno value. */ static char *slurp(const char *path, size_t *len, int *err) { struct stat st; char *buf; size_t used = 0; int fd = open(path, O_RDONLY | O_CLOEXEC); if (fd < 0) { *err = errno; return NULL; } if (fstat(fd, &st) != 0 || S_ISDIR(st.st_mode) || (size_t)st.st_size > READ_FILE_CAP) { *err = S_ISDIR(st.st_mode) ? EISDIR : EFBIG; close(fd); return NULL; } buf = malloc((size_t)st.st_size + 1); while (buf) { ssize_t n = read(fd, buf + used, (size_t)st.st_size - used); if (n < 0 && errno == EINTR) { continue; } if (n <= 0) { break; } used += (size_t)n; if (used == (size_t)st.st_size) { break; } } close(fd); if (!buf) { *err = ENOMEM; return NULL; } buf[used] = '\0'; *len = used; return buf; } static const char *errno_name(int e) { switch (e) { case ENOENT: return "ENOENT"; case EACCES: return "EACCES"; case EISDIR: return "EISDIR"; case ENOTDIR: return "ENOTDIR"; case EFBIG: return "EFBIG"; case ENOMEM: return "ENOMEM"; default: return "EIO"; } } /* Pi's formatSize. */ static void format_size(size_t n, char *out, size_t cap) { if (n < 1024) { (void)snprintf(out, cap, "%zuB", n); } else if (n < 1024 * 1024) { (void)snprintf(out, cap, "%.1fKB", (double)n / 1024.0); } else { (void)snprintf(out, cap, "%.1fMB", (double)n / (1024.0 * 1024.0)); } } /* ---- read ------------------------------------------------------------------- */ static char *tool_read(const char *workspace, const pic_tool_args *a, const pic_tool_hooks *h, int *is_error) { char *path, *data, *out = NULL, size[32]; size_t len = 0, total = 1, start, line, pos, sel_start, bytes = 0, kept = 0, i, line_start, end_line; int err = 0, by_bytes = 0; if (h->started(h->ctx, NULL, 0) != 0) { return NULL; } if (a->bad_input) { return fail(is_error, "%s", a->bad_input); } if (!a->path) { return fail(is_error, "read needs a string input path"); } if (!(path = resolve(workspace, a->path))) { return NULL; } data = slurp(path, &len, &err); if (!data) { out = fail(is_error, "%s: %s, read '%s'", errno_name(err), strerror(err), path); free(path); return out; } for (i = 0; i < len; i++) { total += data[i] == '\n'; } if (a->has_offset && a->offset < 1) { out = fail(is_error, "Offset must be at least 1"); goto done; } start = a->has_offset ? (size_t)a->offset - 1 : 0; if (start >= total) { out = fail(is_error, "Offset %ld is beyond end of file (%zu lines total)", a->offset, total); goto done; } /* Find the byte where line `start` begins. */ for (pos = 0, line = 0; line < start; pos++) { line += data[pos] == '\n'; } sel_start = pos; end_line = a->has_limit && a->limit > 0 && start + (size_t)a->limit < total ? start + (size_t)a->limit : total; /* Keep whole lines while within both limits (Pi's truncateHead). */ for (line = start, line_start = pos; line < end_line; line++) { size_t line_end = line_start; while (line_end < len && data[line_end] != '\n') { line_end++; } { size_t cost = (line_end - line_start) + (kept > 0 ? 1 : 0); if (kept == MAX_LINES) { break; } if (bytes + cost > MAX_BYTES) { by_bytes = 1; if (kept == 0) { format_size(line_end - line_start, size, sizeof size); out = format("[Line %zu is %s, exceeds 50KB limit. Use bash: sed -n '%zup' %s | head -c %d]", start + 1, size, start + 1, a->path, MAX_BYTES); goto done; } break; } bytes += cost; } kept++; line_start = line_end + 1; } { size_t shown_end = start + kept; out = format("%.*s", (int)bytes, data + sel_start); if (out && shown_end < end_line) { char *more = format("%s\n\n[Showing lines %zu-%zu of %zu%s. Use offset=%zu to continue.]", out, start + 1, shown_end, total, by_bytes ? " (50KB limit)" : "", shown_end + 1); free(out); out = more; } else if (out && end_line < total) { char *more = format("%s\n\n[%zu more lines in file. Use offset=%zu to continue.]", out, total - end_line, end_line + 1); free(out); out = more; } } done: free(data); free(path); return out; } /* ---- write ------------------------------------------------------------------ */ static char *tool_write(const char *workspace, const pic_tool_args *a, const pic_tool_hooks *h, int *is_error) { char *path; int e; if (h->started(h->ctx, NULL, 0) != 0) { return NULL; } if (a->bad_input) { return fail(is_error, "%s", a->bad_input); } if (!a->path || !a->content) { return fail(is_error, "write needs string inputs path and content"); } if (!(path = resolve(workspace, a->path))) { return NULL; } if (make_parents(path) != 0) { e = errno; free(path); return fail(is_error, "Could not create directories for %s: %s", a->path, strerror(e)); } e = replace_file(path, a->content, strlen(a->content), 0644); free(path); if (e != 0) { return fail(is_error, "Could not write %s: %s", a->path, strerror(e)); } return format("Successfully wrote to %s", a->path); } /* ---- edit ------------------------------------------------------------------- */ /* Copies s with every CRLF turned into LF. */ static char *to_lf(const char *s, size_t n, size_t *out_len) { char *out = malloc(n + 1); size_t j = 0; if (!out) { return NULL; } for (size_t i = 0; i < n; i++) { if (s[i] == '\r' && i + 1 < n && s[i + 1] == '\n') { continue; } out[j++] = s[i]; } out[j] = '\0'; *out_len = j; return out; } typedef struct { size_t pos, old_len, index; const char *new_text; size_t new_len; char *old_lf, *new_lf; } match; static int by_pos(const void *a, const void *b) { const match *x = a, *y = b; return x->pos < y->pos ? -1 : x->pos > y->pos; } static size_t count_occurrences(const char *hay, size_t n, const char *needle, size_t m, size_t *first) { size_t count = 0, at = 0; *first = 0; while (m > 0 && at + m <= n) { const char *hit = memmem(hay + at, n - at, needle, m); if (!hit) { break; } if (count++ == 0) { *first = (size_t)(hit - hay); } at = (size_t)(hit - hay) + m; } return count; } /* Computes the edited file (the plan) or an error text. */ static char *plan_edit(const char *path_shown, const char *orig, size_t orig_len, const pic_tool_args *a, size_t *plan_len, char **error) { int bom = orig_len >= 3 && memcmp(orig, "\xEF\xBB\xBF", 3) == 0; const char *body = orig + (bom ? 3 : 0); size_t body_len = orig_len - (bom ? 3 : 0), lf_len = 0, out_len = 0, at = 0; int crlf = memmem(body, body_len, "\r\n", 2) != NULL; char *lf = to_lf(body, body_len, &lf_len), *out = NULL, *plan = NULL; match *m = calloc(a->nedits ? a->nedits : 1, sizeof *m); *error = NULL; if (!lf || !m) { goto done; } for (size_t i = 0; i < a->nedits; i++) { size_t n, first; m[i].index = i; if (!(m[i].old_lf = to_lf(a->old_text[i], strlen(a->old_text[i]), &m[i].old_len)) || !(m[i].new_lf = to_lf(a->new_text[i], strlen(a->new_text[i]), &m[i].new_len))) { goto done; } m[i].new_text = m[i].new_lf; if (m[i].old_len == 0) { *error = a->nedits == 1 ? format("oldText must not be empty in %s.", path_shown) : format("edits[%zu].oldText must not be empty in %s.", i, path_shown); goto done; } n = count_occurrences(lf, lf_len, m[i].old_lf, m[i].old_len, &first); if (n == 0) { *error = a->nedits == 1 ? format("Could not find the exact text in %s. The old text must match exactly " "including all whitespace and newlines.", path_shown) : format("Could not find edits[%zu] in %s. The oldText must match exactly " "including all whitespace and newlines.", i, path_shown); goto done; } if (n > 1) { *error = a->nedits == 1 ? format("Found %zu occurrences of the text in %s. The text must be unique. Please " "provide more context to make it unique.", n, path_shown) : format("Found %zu occurrences of edits[%zu] in %s. Each oldText must be unique. " "Please provide more context to make it unique.", n, i, path_shown); goto done; } m[i].pos = first; } qsort(m, a->nedits, sizeof *m, by_pos); for (size_t i = 1; i < a->nedits; i++) { if (m[i].pos < m[i - 1].pos + m[i - 1].old_len) { size_t x = m[i - 1].index < m[i].index ? m[i - 1].index : m[i].index; size_t y = m[i - 1].index < m[i].index ? m[i].index : m[i - 1].index; *error = format("edits[%zu] and edits[%zu] overlap in %s. Merge them into one edit or target disjoint " "regions.", x, y, path_shown); goto done; } } { size_t cap = lf_len + 1; for (size_t i = 0; i < a->nedits; i++) { cap += m[i].new_len; } if (!(out = malloc(cap))) { goto done; } for (size_t i = 0; i < a->nedits; i++) { memcpy(out + out_len, lf + at, m[i].pos - at); out_len += m[i].pos - at; memcpy(out + out_len, m[i].new_text, m[i].new_len); out_len += m[i].new_len; at = m[i].pos + m[i].old_len; } memcpy(out + out_len, lf + at, lf_len - at); out_len += lf_len - at; } if (out_len == lf_len && memcmp(out, lf, lf_len) == 0) { *error = format("No changes made to %s. The replacement produced identical content.", path_shown); goto done; } /* Restore the file's BOM and line endings. */ { size_t extra = 0, j = 0; for (size_t i = 0; crlf && i < out_len; i++) { extra += out[i] == '\n'; } if (!(plan = malloc(out_len + extra + 4))) { goto done; } if (bom) { memcpy(plan, "\xEF\xBB\xBF", 3); j = 3; } for (size_t i = 0; i < out_len; i++) { if (crlf && out[i] == '\n') { plan[j++] = '\r'; } plan[j++] = out[i]; } plan[j] = '\0'; *plan_len = j; } done: for (size_t i = 0; m && i < a->nedits; i++) { free(m[i].old_lf); free(m[i].new_lf); } free(m); free(lf); free(out); if (!plan && !*error) { *error = format("out of memory"); } return plan; } static char *tool_edit(const char *workspace, const pic_tool_args *a, const pic_tool_hooks *h, int *is_error) { char *path, *orig, *plan, *error = NULL, *out; size_t len = 0, plan_len = 0; struct stat st; int err = 0, e; if (h->plan) { /* An earlier attempt computed and journaled the result: write it. */ if (h->started(h->ctx, h->plan, h->plan_len) != 0) { return NULL; } if (!a->path || !(path = resolve(workspace, a->path))) { return fail(is_error, "edit replay lost its path"); } e = replace_file(path, h->plan, h->plan_len, stat(path, &st) == 0 ? st.st_mode & 07777 : 0644); free(path); return e != 0 ? fail(is_error, "Could not write %s: %s", a->path, strerror(e)) : format("Successfully replaced %zu block(s) in %s.", a->nedits, a->path); } if (a->bad_input || !a->path || a->nedits == 0) { if (h->started(h->ctx, NULL, 0) != 0) { return NULL; } return fail(is_error, "%s", a->bad_input ? a->bad_input : !a->path ? "edit needs a string input path" : "Edit tool input is invalid. edits must contain at least one replacement."); } if (!(path = resolve(workspace, a->path))) { return NULL; } if (access(path, R_OK | W_OK) != 0 || !(orig = slurp(path, &len, &err))) { e = err ? err : errno; free(path); if (h->started(h->ctx, NULL, 0) != 0) { return NULL; } return fail(is_error, "Could not edit file: %s. Error code: %s.", a->path, errno_name(e)); } plan = plan_edit(a->path, orig, len, a, &plan_len, &error); free(orig); if (h->started(h->ctx, plan, plan ? plan_len : 0) != 0) { free(plan); free(error); free(path); return NULL; } if (!plan) { free(path); *is_error = 1; return error; } e = replace_file(path, plan, plan_len, stat(path, &st) == 0 ? st.st_mode & 07777 : 0644); free(plan); free(path); out = e != 0 ? fail(is_error, "Could not write %s: %s", a->path, strerror(e)) : format("Successfully replaced %zu block(s) in %s.", a->nedits, a->path); return out; } /* ---- bash ------------------------------------------------------------------- */ static long now_ms(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } /* The last MAX_BYTES of output, plus totals, and the full output in a temp * file in case it has to be truncated. */ typedef struct { char ring[MAX_BYTES]; size_t head, filled, total_bytes, newlines; char last; int spill_fd; char spill[256]; } tail_buf; static void tail_add(tail_buf *t, const char *p, size_t n) { if (t->spill_fd >= 0) { (void)write_all(t->spill_fd, p, n); } for (size_t i = 0; i < n; i++) { char c = p[i] == '\0' ? ' ' : p[i]; /* results are text; a NUL would cut them */ t->ring[t->head] = c; t->head = (t->head + 1) % MAX_BYTES; t->filled += t->filled < MAX_BYTES; t->newlines += c == '\n'; t->last = c; } t->total_bytes += n; } /* Pi's tail truncation: the last whole lines within 2000 lines and 50KB. */ static char *tail_text(tail_buf *t, char **notice) { char *all = malloc(t->filled + 1); size_t len = t->filled, total_lines, kept_lines = 0, s = 0; int by_bytes = t->total_bytes > t->filled; *notice = NULL; if (!all) { return NULL; } for (size_t i = 0; i < len; i++) { all[i] = t->ring[(t->head + MAX_BYTES - len + i) % MAX_BYTES]; } if (len > 0 && all[len - 1] == '\n') { len--; /* a final newline ends the last line; it is not another one */ } all[len] = '\0'; total_lines = t->total_bytes == 0 ? 0 : t->newlines - (t->last == '\n') + 1; if (by_bytes) { char *nl = memchr(all, '\n', len); if (!nl) { char size[32], whole[32]; format_size(len, size, sizeof size); format_size(t->total_bytes, whole, sizeof whole); *notice = format("[Showing last %s of line %zu (line is %s). Full output: %s]", size, total_lines, whole, t->spill); return all; } s = (size_t)(nl - all) + 1; /* drop the partial first line */ } for (size_t i = s; i < len; i++) { kept_lines += all[i] == '\n'; } kept_lines += len > s; while (kept_lines > MAX_LINES) { char *nl = memchr(all + s, '\n', len - s); s = (size_t)(nl - all) + 1; kept_lines--; } if (kept_lines < total_lines) { *notice = format("[Showing lines %zu-%zu of %zu%s. Full output: %s]", total_lines - kept_lines + 1, total_lines, total_lines, t->total_bytes > t->filled ? " (50KB limit)" : "", t->spill); } memmove(all, all + s, len - s + 1); return all; } /* Runs inside the supervisor process. Starts the command in its own process * group only after pic says go, ends when the command itself exits (not when * its output closes) or at the deadline, and kills the whole group if pic dies * first. The result goes back to pic on report_fd: 'O' or 'E', then the text. */ static void supervise(const char *workspace, const char *command, int seconds, int gate_fd, int report_fd) { char go = 0, *out, *notice, *result; int pipefd[2], status = 0, exited = 0, timed_out = 0, output_open = 1, is_error; long deadline = now_ms() + (long)seconds * 1000; tail_buf *t = calloc(1, sizeof *t); const char *shell = access("/bin/bash", X_OK) == 0 ? "/bin/bash" : "/bin/sh"; pid_t child; (void)signal(SIGPIPE, SIG_IGN); if (read(gate_fd, &go, 1) != 1 || go != 'g' || !t || pipe(pipefd) != 0) { _exit(0); /* pic died before committing "started", or no resources: nothing ran */ } { const char *tmpdir = getenv("TMPDIR"); (void)snprintf(t->spill, sizeof t->spill, "%s/pic-bash-XXXXXX", tmpdir && *tmpdir ? tmpdir : "/tmp"); t->spill_fd = mkstemp(t->spill); } child = fork(); if (child < 0) { result = format("Eerror: fork failed: %s", strerror(errno)); if (result) { (void)write_all(report_fd, result, strlen(result)); } _exit(0); } if (child == 0) { (void)setpgid(0, 0); if (chdir(workspace) != 0) { _exit(126); } (void)dup2(pipefd[1], STDOUT_FILENO); (void)dup2(pipefd[1], STDERR_FILENO); close(pipefd[0]); close(pipefd[1]); close(gate_fd); close(report_fd); if (t->spill_fd >= 0) { close(t->spill_fd); } (void)signal(SIGPIPE, SIG_DFL); (void)signal(SIGINT, SIG_DFL); (void)signal(SIGTERM, SIG_DFL); (void)signal(SIGHUP, SIG_DFL); execl(shell, shell, "-c", command, (char *)NULL); _exit(127); } (void)setpgid(child, child); close(pipefd[1]); (void)fcntl(pipefd[0], F_SETFL, fcntl(pipefd[0], F_GETFL) | O_NONBLOCK); /* The command's exit is noticed by waitpid between polls. Waits start at * 1ms and double to 50ms, so a quick command returns almost at once and a * long one costs little CPU. */ for (int wait_ms = 1;; wait_ms = wait_ms < 50 ? wait_ms * 2 : 50) { struct pollfd p[2] = {{gate_fd, POLLIN, 0}, {output_open ? pipefd[0] : -1, POLLIN, 0}}; long left = deadline - now_ms(); if (waitpid(child, &status, WNOHANG) == child) { exited = 1; break; } if (left <= 0) { timed_out = 1; break; } if (poll(p, 2, left < wait_ms ? (int)left : wait_ms) < 0 && errno != EINTR) { break; } if (p[0].revents) { /* pic sends nothing after "go": readable means pic exited. */ (void)kill(-child, SIGKILL); (void)waitpid(child, &status, 0); if (t->spill_fd >= 0) { unlink(t->spill); } _exit(0); } while (output_open) { char buf[4096]; ssize_t n = read(pipefd[0], buf, sizeof buf); if (n > 0) { tail_add(t, buf, (size_t)n); } else if (n == 0 || errno != EINTR) { output_open = n != 0; /* EOF closes; EAGAIN waits for more */ break; } } } /* Descendants do not outlive the command, whatever they did with the pipe. */ (void)kill(-child, SIGKILL); if (!exited) { while (waitpid(child, &status, 0) < 0 && errno == EINTR) { } } /* Keep what the command wrote after the last poll. */ while (output_open) { char buf[4096]; ssize_t n = read(pipefd[0], buf, sizeof buf); if (n > 0) { tail_add(t, buf, (size_t)n); } else if (n == 0 || errno != EINTR) { break; } } close(pipefd[0]); if (t->spill_fd >= 0) { close(t->spill_fd); } out = tail_text(t, ¬ice); if (!notice && t->spill_fd >= 0) { unlink(t->spill); /* nothing was cut: the full output is all here */ } is_error = timed_out || !WIFEXITED(status) || WEXITSTATUS(status) != 0; { char status_line[96] = ""; if (timed_out) { (void)snprintf(status_line, sizeof status_line, "\n\nCommand timed out after %d seconds", seconds); } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { (void)snprintf(status_line, sizeof status_line, "\n\nCommand exited with code %d", WEXITSTATUS(status)); } else if (!WIFEXITED(status)) { (void)snprintf(status_line, sizeof status_line, "\n\nCommand terminated by signal %d", WIFSIGNALED(status) ? WTERMSIG(status) : 0); } result = format("%c%s%s%s%s", is_error ? 'E' : 'O', out && *out ? out : "(no output)", notice ? "\n\n" : "", notice ? notice : "", status_line); } if (result) { (void)write_all(report_fd, result, strlen(result)); } _exit(0); } /* pic forks a supervisor before committing "started"; the supervisor only * starts the command after the commit. The supervisor also keeps pic's * single-writer lock open until it exits, so a restarted pic cannot recover * while a killed command's group is still being torn down. */ static char *tool_bash(const char *workspace, const char *command, int seconds, const pic_tool_hooks *h, int *is_error) { int gate[2], report[2]; sigset_t stop, saved; pid_t sup; char *buf; size_t used = 0, cap = 2 * MAX_BYTES + 1024; if (pipe(gate) != 0) { return h->started(h->ctx, NULL, 0) == 0 ? fail(is_error, "error: cannot start command") : NULL; } if (pipe(report) != 0) { close(gate[0]); close(gate[1]); return h->started(h->ctx, NULL, 0) == 0 ? fail(is_error, "error: cannot start command") : NULL; } /* The supervisor shares pic's process group, so a terminal Ctrl-C or a * group-wide TERM/HUP reaches it too. It must outlive pic long enough to * kill the command, so it ignores them and relies on the gate alone. The * signals stay blocked across fork so none lands before "ignore" is set. */ sigemptyset(&stop); sigaddset(&stop, SIGINT); sigaddset(&stop, SIGTERM); sigaddset(&stop, SIGHUP); (void)sigprocmask(SIG_BLOCK, &stop, &saved); sup = fork(); if (sup == 0) { (void)signal(SIGINT, SIG_IGN); /* also discards any already pending */ (void)signal(SIGTERM, SIG_IGN); (void)signal(SIGHUP, SIG_IGN); (void)sigprocmask(SIG_SETMASK, &saved, NULL); close(gate[1]); close(report[0]); supervise(workspace, command, seconds, gate[0], report[1]); } (void)sigprocmask(SIG_SETMASK, &saved, NULL); close(gate[0]); close(report[1]); if (sup < 0 || h->started(h->ctx, NULL, 0) != 0) { close(gate[1]); close(report[0]); if (sup > 0) { while (waitpid(sup, NULL, 0) < 0 && errno == EINTR) { } return NULL; } return h->started(h->ctx, NULL, 0) == 0 ? fail(is_error, "error: fork failed") : NULL; } /* Allocate before releasing: once "g" is sent the command may run, and its * outcome must not then be reported as a failure to start. */ if (!(buf = malloc(cap + 1)) || write_all(gate[1], "g", 1) != 0) { free(buf); close(gate[1]); close(report[0]); while (waitpid(sup, NULL, 0) < 0 && errno == EINTR) { } return fail(is_error, "error: cannot release command"); } for (;;) { ssize_t n = read(report[0], buf + used, cap - used); if (n < 0 && errno == EINTR) { continue; } if (n <= 0) { break; } used += (size_t)n; if (used == cap) { break; } } buf[used] = '\0'; close(report[0]); while (waitpid(sup, NULL, 0) < 0 && errno == EINTR) { } close(gate[1]); if (used == 0) { free(buf); return fail(is_error, "error: command supervisor produced no result"); } *is_error = buf[0] == 'E'; memmove(buf, buf + 1, used); return buf; } char *pic_tool_run(const char *workspace, const char *tool, const pic_tool_args *args, const pic_tool_hooks *hooks, int *is_error) { *is_error = 0; if (strcmp(tool, "read") == 0) { return tool_read(workspace, args, hooks, is_error); } if (strcmp(tool, "write") == 0) { return tool_write(workspace, args, hooks, is_error); } if (strcmp(tool, "edit") == 0) { return tool_edit(workspace, args, hooks, is_error); } if (strcmp(tool, "bash") == 0) { int seconds = hooks->exec_seconds; if (hooks->started == NULL) { return NULL; } if (args->bad_input || !args->command) { return hooks->started(hooks->ctx, NULL, 0) == 0 ? fail(is_error, "%s", args->bad_input ? args->bad_input : "bash needs a string input command") : NULL; } if (args->has_timeout) { if (args->timeout <= 0 || args->timeout > 86400) { return hooks->started(hooks->ctx, NULL, 0) == 0 ? fail(is_error, "Invalid timeout: must be a finite number of seconds") : NULL; } seconds = (int)args->timeout; } return tool_bash(workspace, args->command, seconds, hooks, is_error); } return hooks->started(hooks->ctx, NULL, 0) == 0 ? fail(is_error, "Tool %s not found", tool) : NULL; }