Skip to content
pi-c Artifact [51b575f617]
Login

Artifact [51b575f617]

Artifact 51b575f617e67f786f101fcef250686a31dbdcbfa227f9db66d154744c492b23:


/* Bounded startup/work sampler for the S0 informational benchmark.
 *
 *   measure --binary PATH --out FILE [--samples N] [--iterations N]
 *           [--deadline SECONDS]
 *
 * One fresh process per sample, timed with CLOCK_MONOTONIC across fork/exec to
 * child exit. The sampler blocks in waitpid(); a SIGALRM deadline interrupts
 * it, so the wait adds no polling floor and the elapsed time is a real
 * measurement. The sampler owns every
 * child: each child is its own process group, and the group is SIGKILLed on
 * timeout, after every normal exit, and when the sampler catches SIGINT,
 * SIGTERM, or SIGHUP. The fixture is given its own deadline so it stops even
 * if the sampler is killed outright.
 *
 * Exit codes: 0 ok, 1 measurement failed (JSON written), 2 usage error.
 */
#define _DEFAULT_SOURCE 1 /* setitimer and struct itimerval */
#define _POSIX_C_SOURCE 200809L

#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

#define MIN_SAMPLES 20U
#define MAX_SAMPLES 200U
#define MAX_ITERATIONS 100000000ULL
#define MAX_DEADLINE 600U /* the driver cap; run-bounded allows 610 outer grace */

#define PATH_MAX_BYTES 4096

struct options {
  const char *binary;
  const char *out;
  unsigned samples;
  unsigned long long iterations;
  unsigned deadline;
};

enum child_result { CHILD_OK, CHILD_EXIT, CHILD_TIMEOUT, CHILD_SPAWN_FAILED };

static volatile sig_atomic_t active_child = 0;
static volatile sig_atomic_t deadline_fired = 0;
static sigset_t block_mask;
static sigset_t old_mask;

static void handle_deadline(int sig) {
  (void)sig;
  deadline_fired = 1;
}

static double monotonic_ms(void) {
  struct timespec ts;
  if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
    return 0.0;
  }
  return (double)ts.tv_sec * 1000.0 + (double)ts.tv_nsec / 1000000.0;
}

static void handle_terminate(int sig) {
  pid_t child = (pid_t)active_child;
  if (child > 0) {
    (void)kill(-child, SIGKILL);
  }
  _exit(128 + sig);
}

/* SIGALRM is delivered without SA_RESTART, so it interrupts the blocking
 * waitpid() at the sample deadline. No signal is blocked in the parent. */
static int install_handlers(void) {
  static const int terminating[] = {SIGINT, SIGTERM, SIGHUP};
  struct sigaction action;
  size_t index;

  memset(&action, 0, sizeof(action));
  action.sa_handler = handle_terminate;
  sigemptyset(&action.sa_mask);
  action.sa_flags = SA_RESTART;
  for (index = 0; index < sizeof(terminating) / sizeof(terminating[0]);
       index++) {
    if (sigaction(terminating[index], &action, NULL) != 0) {
      return 0;
    }
  }
  /* SIGALRM carries the deadline; default disposition would kill us. */
  memset(&action, 0, sizeof(action));
  action.sa_handler = handle_deadline;
  action.sa_flags = 0;
  if (sigaction(SIGALRM, &action, NULL) != 0) {
    return 0;
  }
  /* Held across fork and child registration: a termination signal in that
   * window would otherwise leave the sample child with no owner. */
  sigemptyset(&block_mask);
  sigaddset(&block_mask, SIGINT);
  sigaddset(&block_mask, SIGTERM);
  sigaddset(&block_mask, SIGHUP);
  sigaddset(&block_mask, SIGALRM);
  return 1;
}

static int parse_bounded(const char *text, unsigned long long min,
                         unsigned long long max, unsigned long long *out) {
  char *end = NULL;
  unsigned long long value = 0;
  if (!text || !*text || *text < '0' || *text > '9') {
    return 0;
  }
  errno = 0;
  value = strtoull(text, &end, 10);
  if (errno != 0 || !end || *end != '\0' || value < min || value > max) {
    return 0;
  }
  *out = value;
  return 1;
}

/* Minimal JSON string encoder: paths and child diagnostics are untrusted. */
static void json_string(FILE *out, const char *text) {
  const unsigned char *cursor = (const unsigned char *)(text ? text : "");
  fputc('"', out);
  for (; *cursor; cursor++) {
    switch (*cursor) {
    case '"':
      fputs("\\\"", out);
      break;
    case '\\':
      fputs("\\\\", out);
      break;
    case '\n':
      fputs("\\n", out);
      break;
    case '\r':
      fputs("\\r", out);
      break;
    case '\t':
      fputs("\\t", out);
      break;
    case '\b':
      fputs("\\b", out);
      break;
    case '\f':
      fputs("\\f", out);
      break;
    default:
      if (*cursor < 0x20U) {
        fprintf(out, "\\u%04x", (unsigned)*cursor);
      } else {
        fputc((int)*cursor, out);
      }
    }
  }
  fputc('"', out);
}

/* Kill the whole owned group; harmless when the leader already exited. */
static void kill_group(pid_t pid) {
  if (pid > 0) {
    (void)kill(-pid, SIGKILL);
  }
}

static int run_child(const char *binary, char *const child_argv[],
                     double limit_ms,
                     double *elapsed_ms, unsigned long long *iterations,
                     unsigned long long *checksum, char *stderr_out,
                     size_t stderr_size) {
  char path[] = "/tmp/pi-c-measure-XXXXXX";
  int log_fd = mkstemp(path);
  pid_t pid;
  double started;
  int status = 0;
  enum child_result result = CHILD_SPAWN_FAILED;

  stderr_out[0] = '\0';
  *iterations = 0;
  *checksum = 0;
  *elapsed_ms = 0.0;
  if (log_fd < 0) {
    return CHILD_SPAWN_FAILED;
  }
  unlink(path);

  started = monotonic_ms();
  if (sigprocmask(SIG_BLOCK, &block_mask, &old_mask) != 0) {
    close(log_fd);
    return CHILD_SPAWN_FAILED;
  }
  pid = fork();
  if (pid < 0) {
    (void)sigprocmask(SIG_SETMASK, &old_mask, NULL);
    close(log_fd);
    return CHILD_SPAWN_FAILED;
  }
  if (pid == 0) {
    /* Own process group so the sampler can reap every descendant. Setup
     * failures are fatal here rather than silently inheriting our group. */
    if (setpgid(0, 0) != 0 || dup2(log_fd, STDOUT_FILENO) < 0 ||
        dup2(log_fd, STDERR_FILENO) < 0) {
      _exit(126);
    }
    (void)close(log_fd);
    (void)sigprocmask(SIG_SETMASK, &old_mask, NULL);
    execv(binary, child_argv);
    _exit(127);
  }

  if (setpgid(pid, pid) != 0 && errno != EACCES && errno != ESRCH) {
    /* The child sets its own group; this is a race-free duplicate. A real
     * failure means the group is not ours to kill, so refuse the sample. */
    (void)kill(pid, SIGKILL);
    (void)waitpid(pid, &status, 0);
    (void)sigprocmask(SIG_SETMASK, &old_mask, NULL);
    close(log_fd);
    return CHILD_SPAWN_FAILED;
  }
  active_child = (sig_atomic_t)pid;
  deadline_fired = 0;
  {
    struct itimerval deadline;
    double seconds = limit_ms / 1000.0;
    memset(&deadline, 0, sizeof(deadline));
    deadline.it_value.tv_sec = (time_t)seconds;
    deadline.it_value.tv_usec =
        (suseconds_t)((seconds - (double)deadline.it_value.tv_sec) * 1000000.0);
    if (deadline.it_value.tv_sec == 0 && deadline.it_value.tv_usec == 0) {
      deadline.it_value.tv_usec = 1;
    }
    if (setitimer(ITIMER_REAL, &deadline, NULL) != 0) {
      kill_group(pid);
      (void)waitpid(pid, &status, 0);
      active_child = 0;
      (void)sigprocmask(SIG_SETMASK, &old_mask, NULL);
      close(log_fd);
      return CHILD_SPAWN_FAILED;
    }
  }
  /* Registration is complete; release any signal that arrived meanwhile. */
  if (sigprocmask(SIG_SETMASK, &old_mask, NULL) != 0) {
    kill_group(pid);
    (void)waitpid(pid, &status, 0);
    active_child = 0;
    close(log_fd);
    return CHILD_SPAWN_FAILED;
  }

  for (;;) {
    pid_t waited = waitpid(pid, &status, 0);

    if (waited == pid) {
      result = (WIFEXITED(status) && WEXITSTATUS(status) == 0) ? CHILD_OK
                                                               : CHILD_EXIT;
      break;
    }
    if (waited < 0 && errno == EINTR) {
      /* SIGALRM is the deadline; anything else just resumes the wait. */
      if (deadline_fired || monotonic_ms() - started >= limit_ms) {
        kill_group(pid);
        while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
          /* reap the leader before returning */
        }
        result = CHILD_TIMEOUT;
        break;
      }
      continue;
    }
    if (waited < 0) {
      kill_group(pid);
      (void)waitpid(pid, &status, 0);
      break;
    }
  }
  {
    struct itimerval cancel;
    memset(&cancel, 0, sizeof(cancel));
    (void)setitimer(ITIMER_REAL, &cancel, NULL);
  }

  /* Timestamp at exit, before any cleanup work. */
  *elapsed_ms = monotonic_ms() - started;
  active_child = 0;
  kill_group(pid); /* descendants must not outlive the leader */

  if (result == CHILD_OK || result == CHILD_EXIT || result == CHILD_TIMEOUT) {
    char buffer[512];
    ssize_t read_bytes;
    size_t used = 0;
    (void)lseek(log_fd, 0, SEEK_SET);
    while (used + 1 < sizeof(buffer) &&
           (read_bytes = read(log_fd, buffer + used,
                              sizeof(buffer) - 1 - used)) > 0) {
      used += (size_t)read_bytes;
    }
    buffer[used] = '\0';
    if (result == CHILD_OK && child_argv[1] != NULL &&
        strcmp(child_argv[1], "--work") == 0) {
      unsigned long long seen_iterations = 0;
      unsigned long long seen_checksum = 0;
      if (sscanf(buffer, "work iterations=%llu checksum=%llu",
                 &seen_iterations, &seen_checksum) != 2) {
        result = CHILD_EXIT;
      } else {
        *iterations = seen_iterations;
        *checksum = seen_checksum;
      }
    }
    if (result != CHILD_OK) {
      size_t copy = used < stderr_size - 1 ? used : stderr_size - 1;
      memcpy(stderr_out, buffer, copy);
      stderr_out[copy] = '\0';
    }
  }
  close(log_fd);
  return (int)result;
}

static int compare_double(const void *left, const void *right) {
  double a = *(const double *)left;
  double b = *(const double *)right;
  return (a > b) - (a < b);
}

static double median_of(const double *values, unsigned count) {
  double sorted[MAX_SAMPLES];
  if (count == 0) {
    return 0.0;
  }
  memcpy(sorted, values, count * sizeof(double));
  qsort(sorted, count, sizeof(double), compare_double);
  if (count % 2 == 1) {
    return sorted[count / 2];
  }
  return (sorted[count / 2 - 1] + sorted[count / 2]) / 2.0;
}

static void write_floats(FILE *out, const double *values, unsigned count) {
  unsigned index;
  fputc('[', out);
  for (index = 0; index < count; index++) {
    if (index != 0) {
      fputc(',', out);
    }
    fprintf(out, "%.6f", values[index]);
  }
  fputc(']', out);
}

static int write_failure(const struct options *opt, const char *reason) {
  FILE *out = fopen(opt->out, "w");
  if (!out) {
    fprintf(stderr, "measure: cannot write %s\n", opt->out);
    return 1;
  }
  fputs("{\"status\":\"fail\",\"reason\":", out);
  json_string(out, reason);
  fprintf(out, ",\"samples\":%u,\"iterations\":%llu,\"deadline\":%u}\n",
          opt->samples, opt->iterations, opt->deadline);
  fclose(out);
  fprintf(stderr, "measure: %s\n", reason);
  return 1;
}

static void usage(const char *program) {
  fprintf(stderr,
          "usage: %s --binary PATH --out FILE [--samples N] "
          "[--iterations N] [--deadline SECONDS]\n",
          program);
}

int main(int argc, char **argv) {
  struct options opt = {NULL, NULL, MIN_SAMPLES, 2000ULL, 120U};
  double startup[MAX_SAMPLES];
  double work[MAX_SAMPLES];
  unsigned long long checksum = 0;
  double deadline_at;
  char binary_copy[PATH_MAX_BYTES];
  int index;

  if (!install_handlers()) {
    fprintf(stderr, "measure: cannot install signal handlers\n");
    return 1;
  }

  for (index = 1; index < argc; index++) {
    const char *flag = argv[index];
    const char *value = index + 1 < argc ? argv[index + 1] : NULL;
    unsigned long long parsed = 0;

    if (strcmp(flag, "--binary") == 0 && value) {
      opt.binary = value;
      index++;
    } else if (strcmp(flag, "--out") == 0 && value) {
      opt.out = value;
      index++;
    } else if (strcmp(flag, "--samples") == 0 && value) {
      if (!parse_bounded(value, MIN_SAMPLES, MAX_SAMPLES, &parsed)) {
        usage(argv[0]);
        return 2;
      }
      opt.samples = (unsigned)parsed;
      index++;
    } else if (strcmp(flag, "--iterations") == 0 && value) {
      if (!parse_bounded(value, 1, MAX_ITERATIONS, &parsed)) {
        usage(argv[0]);
        return 2;
      }
      opt.iterations = parsed;
      index++;
    } else if (strcmp(flag, "--deadline") == 0 && value) {
      if (!parse_bounded(value, 1, MAX_DEADLINE, &parsed)) {
        usage(argv[0]);
        return 2;
      }
      opt.deadline = (unsigned)parsed;
      index++;
    } else {
      usage(argv[0]);
      return 2;
    }
  }
  if (!opt.binary || !opt.binary[0] || !opt.out || !opt.out[0]) {
    usage(argv[0]);
    return 2;
  }

  if (strlen(opt.binary) >= sizeof(binary_copy)) {
    fprintf(stderr, "measure: binary path too long\n");
    return 2;
  }
  memcpy(binary_copy, opt.binary, strlen(opt.binary) + 1);
  deadline_at = monotonic_ms() + (double)opt.deadline * 1000.0;
  for (index = 0; index < (int)opt.samples; index++) {
    double limit = deadline_at - monotonic_ms();
    double elapsed = 0.0;
    unsigned long long iterations = 0;
    unsigned long long observed = 0;
    char why[256];
    char *child_argv[] = {binary_copy, "--startup", NULL};
    if (limit <= 0.0) {
      return write_failure(&opt, "execution deadline exceeded");
    }
    if (run_child(opt.binary, child_argv, limit, &elapsed, &iterations,
                  &observed, why, sizeof(why)) != CHILD_OK) {
      char reason[320];
      int written = snprintf(reason, sizeof(reason),
                             "startup sample %d failed: %s", index,
                             why[0] ? why : "child error");
      (void)written;
      return write_failure(&opt, reason);
    }
    startup[index] = elapsed;
  }

  for (index = 0; index < (int)opt.samples; index++) {
    double limit = deadline_at - monotonic_ms();
    double elapsed = 0.0;
    unsigned long long iterations = 0;
    unsigned long long observed = 0;
    char why[256];
    char count[32];
    char self_limit[32];
    long long millis;
    char *child_argv[] = {binary_copy, "--work", count, "--deadline",
                          self_limit, NULL};
    if (limit <= 0.0) {
      return write_failure(&opt, "execution deadline exceeded");
    }
    /* The fixture carries its own deadline, so it stops even if this
       sampler is killed outright and cannot reap the group. */
    millis = (long long)limit;
    if (millis < 1) {
      millis = 1;
    }
    (void)snprintf(count, sizeof(count), "%llu", opt.iterations);
    (void)snprintf(self_limit, sizeof(self_limit), "%lld", millis);
    if (run_child(opt.binary, child_argv, limit, &elapsed, &iterations,
                  &observed, why, sizeof(why)) != CHILD_OK) {
      char reason[320];
      int written = snprintf(reason, sizeof(reason), "work sample %d failed: %s",
                             index, why[0] ? why : "child error");
      (void)written;
      return write_failure(&opt, reason);
    }
    if (iterations != opt.iterations) {
      return write_failure(&opt, "reported iterations differ from requested");
    }
    if (observed == 0) {
      return write_failure(&opt, "zero checksum; workload was elided");
    }
    if (index > 0 && observed != checksum) {
      return write_failure(&opt, "checksum drift across samples");
    }
    checksum = observed;
    work[index] = elapsed;
  }

  {
    FILE *out = fopen(opt.out, "w");
    if (!out) {
      fprintf(stderr, "measure: cannot write %s\n", opt.out);
      return 1;
    }
    fputs("{\"status\":\"ok\",\"binary\":", out);
    json_string(out, opt.binary);
    fprintf(out,
            ",\"samples\":%u,\"iterations\":%u,\"work_iterations\":%llu,"
            "\"deadline\":%u,\"checksum\":%llu,\"startup_median_ms\":%.6f,"
            "\"work_median_ms\":%.6f,\"startup_ms\":",
            opt.samples, (unsigned)opt.iterations, opt.iterations,
            opt.deadline, checksum,
            median_of(startup, opt.samples), median_of(work, opt.samples));
    write_floats(out, startup, opt.samples);
    fputs(",\"work_ms\":", out);
    write_floats(out, work, opt.samples);
    fputs("}\n", out);
    fclose(out);
  }
  printf("ok: %u samples, checksum=%llu\n", opt.samples, checksum);
  return 0;
}