Skip to content

eBPF-based security platform

options: parse every command's options from one table and one parser

Daniel Borkmann96e343b640f2
diff --git a/.agents/skills/coding/SKILL.md b/.agents/skills/coding/SKILL.md
index fb3deb63..701c3120 100644
--- a/.agents/skills/coding/SKILL.md
+++ b/.agents/skills/coding/SKILL.md
@@ -282,6 +282,7 @@ already, or should. The basics:
| SHA-256 | `sha256_buffer()`, or `sha256_init()`, `sha256_update()` and `sha256_final()` over pieces (`util/crypto.h`); `sha256_digest_encode()` and `sha256_digest_decode()` for the `sha256:<hex>` form (`util/hex.h`), `bpm_sha256_digest()` to hash and write it at once (`util/bpm_oci.h`) |
| JSON | `util/json.h`: `json_parse()` with a schema, `json_walk()`, `struct json_emit` |
| Messages | `pr_err()`, `pr_warn()`, `pr_info()`, `pr_audit()` (`util/log.h`) |
+| A command's options | a table of `struct opt_spec` indexed by the command's enum, `OPT_INIT()`, a switch over `opt_next()`, `opt_u64()`, `opt_usage()` and `EXIT_USAGE` (`util/options.h`); `HELP_OPTIONS()` lists the same table in help, and `--list-opts` for completion; never compare `argv[]` by hand |
Code that a second place needs moves into `util/<m>.c`, declared in
`util/<m>.h`, or in `include/shirudo/` for the project's basics, with
diff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rst
index 5fe9a485..a2db9925 100644
--- a/Documentation/contribute/testing/proof-coverage.rst
+++ b/Documentation/contribute/testing/proof-coverage.rst
@@ -959,6 +959,14 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.
- The first command that is the word, else the commands the word
begins, else those that begin it, in table order, as many as the
capacity takes and none written past it
+ * - ``options-next``
+ - ``opt_next()``, ``opt_u64()``
+ - One call from any state a run reaches, on up to three arguments
+ of 0 to 6 bytes, against a table with an option of each kind
+ - Each call takes an argument, so a run ends; an argument or a
+ value lies in an argument; a flag has no value; a value is there
+ and not empty unless the option allows it; no option comes back
+ twice unless it repeats; a number lies in its bounds
* - ``conditions-verdict``
- ``status_verdict()``, ``status_reason()``
- Every input; reasons into 1, 8, 32 and 160 bytes
@@ -1347,7 +1355,9 @@ of :src:`util/upatch_maps.c` that puts a page together from the chunks
``serial_chunk_validate()`` accepted. ``edit_distance()`` of
:src:`util/similar.c` is proven on strings of up to 3 bytes: at its
limit of 64 CBMC ends a run on the code as it is and none on the code
-broken, so no proof of the limit is kept. Of :src:`util/sysinfo.c` the
+broken, so no proof of the limit is kept. ``options-next`` takes
+``parse_u64()`` by the contract ``string-number`` proves and leaves out
+the text of the usage messages, which only ``pr_err()`` reads. Of :src:`util/sysinfo.c` the
proofs cover the image identity's parsers; reading the files they parse,
and the readers of ``/proc`` and the root file system, go to the kernel
and have none.
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rst
index 11f1c842..23e84e67 100644
--- a/Documentation/contribute/testing/test-coverage.rst
+++ b/Documentation/contribute/testing/test-coverage.rst
@@ -777,13 +777,13 @@ signed config image.
Unit suites and fuzz targets
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-The unit suites in :src:`testing/unit/` cover 31 of the modules in
+The unit suites in :src:`testing/unit/` cover 32 of the modules in
:src:`util/`: ``attest``, ``bpm_oci``, ``bpm_package``, ``bpm_state``,
``bpm_tree``, ``bpm_tree_overlap``, ``bpm_tree_state``, ``chain``,
``chain_history``, ``conditions``, ``crypto_openssl``,
``eventlog``, ``format``, ``hex``, ``io``, ``json``, ``kernel_abi``,
``keepalive``, ``keepalive_quote``, ``kernel_build_id``,
-``kernel_release``, ``measured``,
+``kernel_release``, ``measured``, ``options``,
``paths``, ``string``, ``sysinfo``, ``upatch``, ``upatch_decode``,
``upatch_pins``, ``upatch_resolve``, ``upatch_verify`` and ``xdp``, and
``overflow`` the arithmetic of
diff --git a/Makefile.shirudo b/Makefile.shirudo
index 5decad84..0e91b554 100644
--- a/Makefile.shirudo
+++ b/Makefile.shirudo
@@ -284,6 +284,7 @@ UTIL_SRCS := \
util/sysinfo.c \
util/similar.c \
util/help.c \
+ util/options.c \
util/timefmt.c \
util/conditions.c \
util/keepalive.c \
diff --git a/testing/proofs/cbmc/options-next.c b/testing/proofs/cbmc/options-next.c
new file mode 100644
index 00000000..ce9d1552
--- /dev/null
+++ b/testing/proofs/cbmc/options-next.c
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * opt_next() of util/options.c from every state a run of calls reaches,
+ * on every command line of up to ARGS_MAX arguments of up to LEN bytes,
+ * against a table with an option of each kind: each call takes at least
+ * one argument, so a run ends, what it hands back lies in an argument, a
+ * flag has no value, a value is there and not empty unless the option
+ * allows it, and no option comes back twice unless it repeats.
+ */
+
+#include <errno.h>
+#include <stdbool.h>
+
+#include "proof.h"
+#include "../../../util/options.c"
+
+#define ARGS_MAX 3
+
+enum { P_A, P_BB, P_C, P_D, P_N, P_COUNT };
+
+static const struct opt_spec specs[] = {
+ [P_A] = { "--a", 'a', 0, "<v>", "a value" },
+ [P_BB] = { "--bb", 0, 0, NULL, "a flag" },
+ [P_C] = { "--c", 0, OPT_OPTIONAL, "<v>", "a value after = or none" },
+ [P_D] = { "--d", 0, OPT_REPEAT | OPT_EMPTY, "<v>", "repeats, may be empty" },
+ [P_N] = { "--n", 0, 0, "<n>", "a number" },
+};
+
+void pr_err(const char *fmt, ...)
+{
+}
+
+/* The messages are not read here; the format proofs cover the text. */
+int vstrsprintf(char *buf, size_t size, const char *fmt, va_list ap)
+{
+ if (size)
+ buf[0] = '\0';
+ return 0;
+}
+
+/* The contract string-number proves: a number up to max, or an error. */
+int parse_u64(const char *s, size_t len, __u64 max, __u64 *out)
+{
+ __u64 v;
+ int ret;
+
+ __CPROVER_assert(__CPROVER_r_ok(s, len), "the digits are readable");
+ if (ret)
+ return ret < 0 ? ret : -EINVAL;
+ __CPROVER_assume(v <= max);
+ *out = v;
+ return 0;
+}
+
+void print_help(const struct help *h)
+{
+}
+
+void help_suggest(const char *bad, const char *const *names, size_t n_names)
+{
+ __CPROVER_assert(n_names <= OPT_MAX, "the names fit");
+ __CPROVER_assert(strlen(bad) <= SIMILAR_MAX_LEN, "the word fits");
+}
+
+static const char *argv[ARGS_MAX];
+static size_t lens[ARGS_MAX];
+
+static const char *any_string(size_t *len)
+{
+ char *s;
+
+ __CPROVER_assume(*len <= LEN);
+ s = any_bytes(*len + 1);
+ __CPROVER_assume(!s[*len] && strnlen(s, *len) == *len);
+ return s;
+}
+
+static bool in_args(const char *v, int argc)
+{
+ int k;
+
+ for (k = 0; k < argc; k++)
+ if (__CPROVER_same_object(v, argv[k]) &&
+ __CPROVER_POINTER_OFFSET(v) <= lens[k])
+ return true;
+ return false;
+}
+
+void harness(void)
+{
+ bool checked, args_only;
+ const struct opt_spec *s;
+ int argc, i, next, opt;
+ __u64 given_before, n;
+ struct opt_parser p;
+
+ __CPROVER_assume(argc >= 0 && argc <= ARGS_MAX);
+ for (i = 0; i < argc; i++) {
+ size_t len;
+
+ argv[i] = any_string(&len);
+ lens[i] = len;
+ }
+ OPT_INIT(&p, "proof", specs, NULL, argc, argv, 0);
+ /* Any state a run of calls reaches: the next argument, what came. */
+ __CPROVER_assume(next >= 0 && next <= argc);
+ __CPROVER_assume(!(given_before >> P_COUNT));
+ p.next = next;
+ p.given = given_before;
+ p.checked = checked;
+ p.args_only = args_only;
+
+ opt = opt_next(&p);
+ __CPROVER_assert(p.next <= argc, "never past the arguments");
+ if (opt == OPT_END) {
+ __CPROVER_assert(p.next == argc,
+ "the end only where no argument is left");
+ return;
+ }
+ if (opt == OPT_DONE || opt == OPT_USAGE)
+ return;
+ __CPROVER_assert(p.next > next, "every call takes an argument");
+ if (opt == OPT_ARG) {
+ __CPROVER_assert(p.value == argv[p.next - 1],
+ "an argument is the one it took");
+ return;
+ }
+ __CPROVER_assert(opt >= 0 && opt < P_COUNT, "an option of the table");
+ __CPROVER_assert(opt_given(&p, opt), "what comes back is marked given");
+ s = &specs[opt];
+ if (!s->metavar)
+ __CPROVER_assert(!p.value, "a flag has no value");
+ else if (p.value)
+ __CPROVER_assert(in_args(p.value, argc) &&
+ (*p.value || (s->flags & OPT_EMPTY)),
+ "a value in an argument, empty only where allowed");
+ else
+ __CPROVER_assert(s->flags & OPT_OPTIONAL,
+ "only an optional value may be left out");
+ __CPROVER_assert(!(given_before & (1ULL << opt)) ||
+ (s->flags & OPT_REPEAT),
+ "an option comes once unless it repeats");
+ if (opt == P_N && !opt_u64(&p, 1, 512, &n))
+ __CPROVER_assert(n >= 1 && n <= 512, "a number in bounds");
+}
diff --git a/testing/proofs/cbmc/proofs.list b/testing/proofs/cbmc/proofs.list
index 37e6d095..61f61680 100644
--- a/testing/proofs/cbmc/proofs.list
+++ b/testing/proofs/cbmc/proofs.list
@@ -96,6 +96,7 @@ paths-pin --unwind 32 LEN=0,1,28-35
similar-distance --max-field-sensitivity-array-size 65 --unwind 8 --unwindset memcpy.0:18 LEN=0-15
similar-suggest --object-bits 10 --max-field-sensitivity-array-size 65 --unwind 8 --unwindset memcpy.0:14 LEN=0-8,18-26
similar-resolve --object-bits 10 --unwind 8
+options-next --object-bits 12 --unwind 8 LEN=0-6
config-evidence-event --unwind 1 --unwindset harness.0:33,same_event.0:33,hex_digits.0:65,room_for.0:10,on_event.0:4,hex_decode.0:33,strlen.0:66 LEN=0,1,15,16,128,4095,4096
config-evidence-parse --unwind 1 --unwindset config_evidence_parse.0:7,on_event.0:4,replay.0:4,hex_decode.0:33,strlen.0:66,strcmp.0:15,named.0:7,json_parse.0:7,json_parse.1:4,give_event.0:4,give_text.0:66,any_document.0:4,whole.0:4,in_order.0:4,hex_digits.0:65,spells.0:33,blank.0:33,check_as_said.0:4,check_as_said.1:33 --memory-leak-check --slice-formula LEN=0-2
config-evidence-roundtrip --unwind 1 --unwindset config_evidence_emit.0:4,hex_encode.0:33,config_evidence_parse.0:7,on_event.0:4,replay.0:4,hex_decode.0:33,strlen.0:66,strcmp.0:15,named.0:7,json_parse.0:7,json_parse.1:4,give_event.0:4,give_text.0:66,json_kv_string.0:66,sequence_overflows.0:4,replays.0:4,same.0:33,blank.0:33,check_read_back.0:4 --memory-leak-check --slice-formula LEN=0-2
diff --git a/testing/unit/options.c b/testing/unit/options.c
new file mode 100644
index 00000000..34907378
--- /dev/null
+++ b/testing/unit/options.c
@@ -0,0 +1,234 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <stdio.h>
+
+#include "help.h"
+#include "options.h"
+#include "unit.h"
+
+enum {
+ T_CERT,
+ T_FORCE,
+ T_OUTPUT,
+ T_JSON,
+ T_ADD,
+ T_TAG,
+ T_COUNT,
+};
+
+static const struct opt_spec specs[] = {
+ [T_CERT] = { "--cert", 0, 0, "<path>", "a certificate" },
+ [T_FORCE] = { "--force", 'f', 0, NULL, "overwrite" },
+ [T_OUTPUT] = { "--output", 'o', 0, "<path>", "where to write" },
+ [T_JSON] = { "--json", 0, OPT_OPTIONAL, "<path>", "JSON, to a file" },
+ [T_ADD] = { "--add", 0, OPT_REPEAT, "<name>", "one more name" },
+ [T_TAG] = { "--tag", 0, OPT_EMPTY, "<tag>", "a tag, may be empty" },
+ [T_COUNT] = { "--count", 0, 0, "<n>", "how many" },
+};
+
+static void parse(struct opt_parser *p, const char *const *argv, int argc)
+{
+ OPT_INIT(p, "test", specs, NULL, argc, argv, 0);
+}
+
+static void both_value_forms_give_the_same(void)
+{
+ static const char *const argv[] = { "--cert", "a.der", "--output=b" };
+ struct opt_parser p;
+
+ parse(&p, argv, 3);
+ ASSERT_EQ(opt_next(&p), T_CERT);
+ EXPECT_STREQ(p.value, "a.der");
+ ASSERT_EQ(opt_next(&p), T_OUTPUT);
+ EXPECT_STREQ(p.value, "b");
+ EXPECT_EQ(opt_next(&p), OPT_END);
+ EXPECT_TRUE(opt_given(&p, T_CERT));
+ EXPECT_FALSE(opt_given(&p, T_FORCE));
+}
+
+static void a_value_must_be_there_and_not_empty(void)
+{
+ static const char *const last[] = { "--cert" };
+ static const char *const empty[] = { "--cert=" };
+ static const char *const tag[] = { "--tag=" };
+ struct opt_parser p;
+
+ parse(&p, last, 1);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+ parse(&p, empty, 1);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+ parse(&p, tag, 1);
+ ASSERT_EQ(opt_next(&p), T_TAG);
+ EXPECT_STREQ(p.value, "");
+}
+
+static void a_flag_takes_no_value(void)
+{
+ static const char *const ok[] = { "-f" };
+ static const char *const bad[] = { "--force=yes" };
+ struct opt_parser p;
+
+ parse(&p, ok, 1);
+ EXPECT_EQ(opt_next(&p), T_FORCE);
+ EXPECT_TRUE(!p.value);
+ parse(&p, bad, 1);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+}
+
+static void an_option_comes_once_unless_it_repeats(void)
+{
+ static const char *const twice[] = { "--cert", "a", "--cert=b" };
+ static const char *const alias[] = { "-f", "--force" };
+ static const char *const repeat[] = { "--add", "x", "--add=y" };
+ struct opt_parser p;
+
+ parse(&p, twice, 3);
+ ASSERT_EQ(opt_next(&p), T_CERT);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+ parse(&p, alias, 2);
+ ASSERT_EQ(opt_next(&p), T_FORCE);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+ parse(&p, repeat, 3);
+ ASSERT_EQ(opt_next(&p), T_ADD);
+ EXPECT_STREQ(p.value, "x");
+ ASSERT_EQ(opt_next(&p), T_ADD);
+ EXPECT_STREQ(p.value, "y");
+}
+
+static void unknown_and_glued_options_are_refused(void)
+{
+ static const char *const bad[][1] = {
+ { "--crt" }, { "--cert-file=x" }, { "-x" }, { "-oout" },
+ { "-fo" }, { "--c" },
+ };
+ struct opt_parser p;
+ size_t i;
+
+ for (i = 0; i < ARRAY_SIZE(bad); i++) {
+ parse(&p, bad[i], 1);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+ }
+}
+
+static void arguments_interleave_and_double_dash_ends_options(void)
+{
+ static const char *const argv[] = { "pkg", "-o", "x", "-", "--", "--cert", "-f" };
+ struct opt_parser p;
+
+ parse(&p, argv, 7);
+ ASSERT_EQ(opt_next(&p), OPT_ARG);
+ EXPECT_STREQ(p.value, "pkg");
+ ASSERT_EQ(opt_next(&p), T_OUTPUT);
+ EXPECT_STREQ(p.value, "x");
+ ASSERT_EQ(opt_next(&p), OPT_ARG);
+ EXPECT_STREQ(p.value, "-");
+ ASSERT_EQ(opt_next(&p), OPT_ARG);
+ EXPECT_STREQ(p.value, "--cert");
+ ASSERT_EQ(opt_next(&p), OPT_ARG);
+ EXPECT_STREQ(p.value, "-f");
+ EXPECT_EQ(opt_next(&p), OPT_END);
+}
+
+static void an_optional_value_comes_after_equals_alone(void)
+{
+ static const char *const argv[] = { "--json", "file", "--output", "o" };
+ static const char *const eq[] = { "--json=log.ndjson" };
+ struct opt_parser p;
+
+ parse(&p, argv, 4);
+ ASSERT_EQ(opt_next(&p), T_JSON);
+ EXPECT_TRUE(!p.value);
+ ASSERT_EQ(opt_next(&p), OPT_ARG);
+ EXPECT_STREQ(p.value, "file");
+ parse(&p, eq, 1);
+ ASSERT_EQ(opt_next(&p), T_JSON);
+ EXPECT_STREQ(p.value, "log.ndjson");
+}
+
+static void help_and_the_option_list_end_parsing(void)
+{
+ static const char *const help[] = { "--cert", "a", "-h", "--bogus" };
+ static const char *const list[] = { "--list-opts" };
+ struct opt_parser p;
+ FILE *saved = stdout;
+
+ parse(&p, help, 4);
+ ASSERT_EQ(opt_next(&p), T_CERT);
+ EXPECT_EQ(opt_next(&p), OPT_DONE);
+ stdout = fopen("/dev/null", "w");
+ ASSERT_TRUE(stdout);
+ parse(&p, list, 1);
+ EXPECT_EQ(opt_next(&p), OPT_DONE);
+ EXPECT_EQ(fclose(stdout), 0);
+ stdout = saved;
+}
+
+static void a_number_is_bounded(void)
+{
+ static const char *const ok[] = { "--count", "512" };
+ static const char *const low[] = { "--count=0" };
+ static const char *const high[] = { "--count=513" };
+ static const char *const word[] = { "--count=ten" };
+ static const char *const *const bad[] = { low, high, word };
+ struct opt_parser p;
+ __u64 n = 0;
+ size_t i;
+
+ parse(&p, ok, 2);
+ ASSERT_EQ(opt_next(&p), T_COUNT);
+ ASSERT_EQ(opt_u64(&p, 1, 512, &n), 0);
+ EXPECT_UEQ(n, 512);
+ for (i = 0; i < ARRAY_SIZE(bad); i++) {
+ parse(&p, bad[i], 1);
+ ASSERT_EQ(opt_next(&p), T_COUNT);
+ EXPECT_EQ(opt_u64(&p, 1, 512, &n), OPT_USAGE);
+ }
+ parse(&p, ok, 0);
+ EXPECT_EQ(opt_next(&p), OPT_END);
+ EXPECT_EQ(opt_u64(&p, 1, 512, &n), OPT_USAGE);
+}
+
+static void a_malformed_table_is_refused_before_any_argument(void)
+{
+ static const struct opt_spec hole[] = {
+ [1] = { "--a", 0, 0, NULL, "a" },
+ };
+ static const struct opt_spec twice[] = {
+ { "--a", 0, 0, NULL, "a" },
+ { "--a", 0, 0, "<x>", "a again" },
+ };
+ static const struct opt_spec flag_with_flags[] = {
+ { "--a", 0, OPT_EMPTY, NULL, "a" },
+ };
+ static const struct opt_spec no_dashes[] = {
+ { "a", 0, 0, NULL, "a" },
+ };
+ static const char *const argv[] = { "arg" };
+ struct opt_parser p;
+
+ OPT_INIT(&p, "test", hole, NULL, 1, argv, 0);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+ OPT_INIT(&p, "test", twice, NULL, 1, argv, 0);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+ OPT_INIT(&p, "test", flag_with_flags, NULL, 1, argv, 0);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+ OPT_INIT(&p, "test", no_dashes, NULL, 1, argv, 0);
+ EXPECT_EQ(opt_next(&p), OPT_USAGE);
+}
+
+static const struct unit_case cases[] = {
+ UNIT_CASE(both_value_forms_give_the_same),
+ UNIT_CASE(a_value_must_be_there_and_not_empty),
+ UNIT_CASE(a_flag_takes_no_value),
+ UNIT_CASE(an_option_comes_once_unless_it_repeats),
+ UNIT_CASE(unknown_and_glued_options_are_refused),
+ UNIT_CASE(arguments_interleave_and_double_dash_ends_options),
+ UNIT_CASE(an_optional_value_comes_after_equals_alone),
+ UNIT_CASE(help_and_the_option_list_end_parsing),
+ UNIT_CASE(a_number_is_bounded),
+ UNIT_CASE(a_malformed_table_is_refused_before_any_argument),
+ {}
+};
+
+UNIT_SUITE(options, cases);
diff --git a/util/help.c b/util/help.c
index 7b527dc5..60965d91 100644
--- a/util/help.c
+++ b/util/help.c
@@ -9,8 +9,10 @@
#include <string.h>
#include <shirudo/misc.h>
+#include <shirudo/string.h>
#include "help.h"
+#include "options.h"
#include "similar.h"
#define SUBCMD_MAX 32
@@ -79,42 +81,71 @@ void print_subcmd_list(const struct help_item *items,
printf("%s\n", items[i].name);
}
+/* An option as help shows it: "-o, --output <path>", "--json[=<path>]". */
+static const char *option_label(const struct opt_spec *o, char *buf,
+ size_t size)
+{
+ char alias[5] = "";
+ int ret;
+
+ if (o->short_name &&
+ strsprintf(alias, sizeof(alias), "-%c, ", o->short_name) < 0)
+ return o->name;
+ if (!o->metavar)
+ ret = strsprintf(buf, size, "%s%s", alias, o->name);
+ else if (o->flags & OPT_OPTIONAL)
+ ret = strsprintf(buf, size, "%s%s[=%s]", alias, o->name,
+ o->metavar);
+ else
+ ret = strsprintf(buf, size, "%s%s %s", alias, o->name,
+ o->metavar);
+ return ret < 0 ? o->name : buf;
+}
+
+static void print_row(const char *name, const char *summary, size_t w)
+{
+ size_t indent = 2 + w;
+ size_t avail = indent < HELP_WIDTH ? HELP_WIDTH - indent : 1;
+
+ fprintf(stderr, " %-*s", (int)w, name);
+ wrap_print(summary, indent, avail);
+}
+
+static void print_section(const struct help_section *s)
+{
+ char label[96];
+ size_t i, w = 0;
+
+ if (!s->n_items && !s->n_options)
+ return;
+ /*
+ * Per section, so an Options section reads as cleanly as a
+ * Subcommands one.
+ */
+ for (i = 0; i < s->n_items; i++)
+ w = max(w, strlen(s->items[i].name));
+ for (i = 0; i < s->n_options; i++)
+ w = max(w, strlen(option_label(&s->options[i], label,
+ sizeof(label))));
+ w += 2;
+ fprintf(stderr, "\n%s\n", s->header);
+ for (i = 0; i < s->n_items; i++)
+ print_row(s->items[i].name, s->items[i].summary, w);
+ for (i = 0; i < s->n_options; i++)
+ print_row(option_label(&s->options[i], label, sizeof(label)),
+ s->options[i].summary, w);
+}
+
void print_help(const struct help *h)
{
- size_t i, j;
+ size_t i;
if (h->usage)
fprintf(stderr, "usage: %s\n", h->usage);
if (h->summary && *h->summary)
fprintf(stderr, "\n%s\n", h->summary);
-
- for (i = 0; i < h->n_sections; i++) {
- const struct help_section *s = &h->sections[i];
- size_t w = 0;
-
- if (s->n_items == 0)
- continue;
- /*
- * Per section, so an Options section reads as cleanly as a
- * Subcommands one.
- */
- for (j = 0; j < s->n_items; j++) {
- size_t l = strlen(s->items[j].name);
-
- if (l > w)
- w = l;
- }
- w += 2;
- fprintf(stderr, "\n%s\n", s->header);
- for (j = 0; j < s->n_items; j++) {
- size_t indent = 2 + w;
- size_t avail = indent < HELP_WIDTH ?
- HELP_WIDTH - indent : 1;
-
- fprintf(stderr, " %-*s", (int)w, s->items[j].name);
- wrap_print(s->items[j].summary, indent, avail);
- }
- }
+ for (i = 0; i < h->n_sections; i++)
+ print_section(&h->sections[i]);
if (h->footer && *h->footer)
fprintf(stderr, "\n%s\n", h->footer);
}
diff --git a/util/help.h b/util/help.h
index 48d7de8d..c9b0fa25 100644
--- a/util/help.h
+++ b/util/help.h
@@ -14,15 +14,20 @@
#include <shirudo/misc.h>
+struct opt_spec;
+
struct help_item {
const char *name;
const char *summary;
};
+/* A section lists items, or the options of a command's opt_spec table. */
struct help_section {
const char *header;
const struct help_item *items;
size_t n_items;
+ const struct opt_spec *options;
+ size_t n_options;
};
/* A section named h listing the items of the array a. */
@@ -30,6 +35,11 @@ struct help_section {
{ .header = (h), .items = (a), \
.n_items = sizeof(a) / sizeof((a)[0]) + __must_be_array(a) }
+/* A section named h listing the options of the opt_spec array a. */
+#define HELP_OPTIONS(h, a) \
+ { .header = (h), .options = (a), \
+ .n_options = sizeof(a) / sizeof((a)[0]) + __must_be_array(a) }
+
struct help {
const char *usage;
const char *summary;
diff --git a/util/options.c b/util/options.c
new file mode 100644
index 00000000..c2b329d6
--- /dev/null
+++ b/util/options.c
@@ -0,0 +1,222 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * The one parser of command line options, and the rules it holds every
+ * command to.
+ */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <shirudo/misc.h>
+#include <shirudo/string.h>
+
+#include "help.h"
+#include "log.h"
+#include "options.h"
+#include "similar.h"
+
+int opt_usage(const struct opt_parser *p, const char *fmt, ...)
+{
+ char msg[512];
+ va_list ap;
+ int ret;
+
+ va_start(ap, fmt);
+ ret = vstrsprintf(msg, sizeof(msg), fmt, ap);
+ va_end(ap);
+ pr_err("%s: %s", p->command, ret < 0 ? fmt : msg);
+ return OPT_USAGE;
+}
+
+void opt_init(struct opt_parser *p, const char *command,
+ const struct opt_spec *specs, size_t n_specs,
+ const struct help *help, int argc, const char *const *argv,
+ int first)
+{
+ *p = (struct opt_parser) {
+ .command = command,
+ .specs = specs,
+ .n_specs = n_specs,
+ .help = help,
+ .argv = argv,
+ .argc = argc,
+ .next = first,
+ .opt = OPT_END,
+ };
+}
+
+/*
+ * A table with a hole, a name twice, or a flag marked as taking a value
+ * would leave an option unreachable or read wrong, whatever the command
+ * line; refuse it before any argument is read.
+ */
+static bool specs_valid(const struct opt_spec *specs, size_t n)
+{
+ size_t i, j;
+
+ if (n > OPT_MAX)
+ return false;
+ for (i = 0; i < n; i++) {
+ const struct opt_spec *s = &specs[i];
+
+ if (!s->name || !str_has_prefix(s->name, "--") ||
+ !s->name[2] || strchr(s->name, '=') || !s->summary)
+ return false;
+ if (!s->metavar && (s->flags & (OPT_EMPTY | OPT_OPTIONAL)))
+ return false;
+ for (j = 0; j < i; j++) {
+ if (!strcmp(s->name, specs[j].name) ||
+ (s->short_name &&
+ s->short_name == specs[j].short_name))
+ return false;
+ }
+ }
+ return true;
+}
+
+/*
+ * The index of the option arg names, -1 for none, and in *eq what follows
+ * its = where it has one. A short option stands alone: -o, never -ovalue
+ * or -fo.
+ */
+static int spec_find(const struct opt_parser *p, const char *arg,
+ const char **eq)
+{
+ size_t i, len;
+
+ *eq = NULL;
+ if (arg[1] != '-') {
+ if (arg[2])
+ return -1;
+ for (i = 0; i < p->n_specs; i++)
+ if (p->specs[i].short_name == arg[1])
+ return (int)i;
+ return -1;
+ }
+ len = strcspn(arg, "=");
+ if (arg[len])
+ *eq = arg + len + 1;
+ for (i = 0; i < p->n_specs; i++) {
+ const char *name = p->specs[i].name;
+
+ if (strlen(name) == len && !strncmp(name, arg, len))
+ return (int)i;
+ }
+ return -1;
+}
+
+static int opt_unknown(const struct opt_parser *p, const char *arg)
+{
+ size_t i, len = arg[1] == '-' ? strcspn(arg, "=") : strlen(arg);
+ const char *names[OPT_MAX];
+ char bad[SIMILAR_MAX_LEN + 1];
+
+ pr_err("%s: unknown option '%.*s'", p->command, (int)len, arg);
+ if (len >= sizeof(bad))
+ return OPT_USAGE;
+ memcpy(bad, arg, len);
+ bad[len] = '\0';
+ for (i = 0; i < p->n_specs; i++)
+ names[i] = p->specs[i].name;
+ help_suggest(bad, names, p->n_specs);
+ return OPT_USAGE;
+}
+
+/* What bash completion reads: "--json=\t<path>", "--cert\t<path>", "-o". */
+static int opt_list(const struct opt_parser *p)
+{
+ size_t i;
+
+ for (i = 0; i < p->n_specs; i++) {
+ const struct opt_spec *s = &p->specs[i];
+ const char *eq = s->flags & OPT_OPTIONAL ? "=" : "";
+
+ if (s->short_name)
+ printf("-%c%s%s\n", s->short_name,
+ s->metavar ? "\t" : "",
+ s->metavar ? s->metavar : "");
+ if (s->metavar)
+ printf("%s%s\t%s\n", s->name, eq, s->metavar);
+ else
+ printf("%s\n", s->name);
+ }
+ return OPT_DONE;
+}
+
+static int opt_take_value(struct opt_parser *p, const struct opt_spec *s,
+ const char *eq)
+{
+ if (!s->metavar)
+ return eq ? opt_usage(p, "%s takes no value", s->name) : 0;
+ if (eq)
+ p->value = eq;
+ else if (s->flags & OPT_OPTIONAL)
+ return 0;
+ else if (p->next < p->argc)
+ p->value = p->argv[p->next++];
+ else
+ return opt_usage(p, "%s takes a value", s->name);
+ if (!*p->value && !(s->flags & OPT_EMPTY))
+ return opt_usage(p, "%s takes a value, not an empty one",
+ s->name);
+ return 0;
+}
+
+int opt_next(struct opt_parser *p)
+{
+ const struct opt_spec *s;
+ const char *arg, *eq;
+ int opt;
+
+ if (!p->checked && !specs_valid(p->specs, p->n_specs))
+ return opt_usage(p, "the table of its options is malformed");
+ p->checked = true;
+ p->value = NULL;
+ p->opt = OPT_END;
+ for (;;) {
+ if (p->next >= p->argc)
+ return OPT_END;
+ arg = p->argv[p->next++];
+ if (p->args_only || arg[0] != '-' || !arg[1]) {
+ p->value = arg;
+ return OPT_ARG;
+ }
+ if (strcmp(arg, "--"))
+ break;
+ p->args_only = true;
+ }
+ if (!strcmp(arg, "-h") || !strcmp(arg, "--help")) {
+ if (p->help)
+ print_help(p->help);
+ return OPT_DONE;
+ }
+ if (!strcmp(arg, "--list-opts"))
+ return opt_list(p);
+ opt = spec_find(p, arg, &eq);
+ if (opt < 0)
+ return opt_unknown(p, arg);
+ s = &p->specs[opt];
+ if (opt_given(p, opt) && !(s->flags & OPT_REPEAT))
+ return opt_usage(p, "%s given twice", s->name);
+ if (opt_take_value(p, s, eq))
+ return OPT_USAGE;
+ p->given |= 1ULL << opt;
+ p->opt = opt;
+ return opt;
+}
+
+int opt_u64(const struct opt_parser *p, __u64 min, __u64 max, __u64 *out)
+{
+ __u64 v;
+
+ if (p->opt < 0 || !p->value)
+ return opt_usage(p, "no option value to read as a number");
+ if (parse_u64(p->value, strlen(p->value), max, &v) || v < min)
+ return opt_usage(p, "%s takes a number from %llu to %llu",
+ p->specs[p->opt].name, min, max);
+ *out = v;
+ return 0;
+}
diff --git a/util/options.h b/util/options.h
new file mode 100644
index 00000000..5781e39d
--- /dev/null
+++ b/util/options.h
@@ -0,0 +1,105 @@
+/* SPDX-License-Identifier: BSD-2-Clause */
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * The options of every command, from a table indexed by the command's
+ * own enum of them, and the rules all of them follow.
+ */
+
+#ifndef SHIRUDO_OPTIONS_H
+#define SHIRUDO_OPTIONS_H
+
+#include <stdbool.h>
+#include <stddef.h>
+
+#include <shirudo/compiler.h>
+#include <shirudo/misc.h>
+#include <shirudo/types.h>
+
+/* The exit status of every usage error. */
+#define EXIT_USAGE 2
+
+/* The most options one command has: a bit each in opt_parser.given. */
+#define OPT_MAX 64
+
+#define OPT_REPEAT (1u << 0) /* may be given more than once */
+#define OPT_EMPTY (1u << 1) /* may be given an empty value */
+#define OPT_OPTIONAL (1u << 2) /* takes a value after = alone, or none */
+
+/*
+ * One option. Where metavar names a value, the option takes one as the
+ * next argument or after =; where metavar is NULL, it is a flag.
+ */
+struct opt_spec {
+ const char *name; /* "--cert" */
+ char short_name; /* 'o' for -o, or 0 */
+ __u32 flags;
+ const char *metavar; /* "<path>" */
+ const char *summary;
+};
+
+/* What opt_next() returns besides the index of an option. */
+#define OPT_END (-1) /* no argument is left */
+#define OPT_ARG (-2) /* an argument, in value */
+#define OPT_DONE (-3) /* help or the option list printed: exit 0 */
+#define OPT_USAGE (-4) /* a usage error, already reported */
+
+struct help;
+
+struct opt_parser {
+ const char *command; /* "attest verify" */
+ const struct opt_spec *specs;
+ size_t n_specs;
+ const struct help *help;
+ const char *const *argv;
+ int argc;
+ int next;
+ bool checked;
+ bool args_only; /* after "--" */
+ __u64 given;
+ int opt; /* the option last returned */
+ const char *value;
+};
+
+/*
+ * A parser of argv from first on, against the n_specs options of specs,
+ * whose index is the command's enum of them. Its errors start with
+ * command, and -h or --help prints help.
+ */
+void opt_init(struct opt_parser *p, const char *command,
+ const struct opt_spec *specs, size_t n_specs,
+ const struct help *help, int argc, const char *const *argv,
+ int first);
+
+#define OPT_INIT(p, command, specs, help, argc, argv, first) \
+ opt_init(p, command, specs, \
+ sizeof(specs) / sizeof((specs)[0]) + __must_be_array(specs), \
+ help, argc, argv, first)
+
+/*
+ * The index of the next option, with value set where it takes one, NULL
+ * for an OPT_OPTIONAL one given without; otherwise one of the OPT_ codes
+ * above. An unknown option, a value missing, empty or given to a flag,
+ * and an option given twice are usage errors. --list-opts prints the
+ * options, one a line, a value's metavar after a tab, for completion.
+ */
+int opt_next(struct opt_parser *p);
+
+/* Whether the option of index opt was given. */
+static inline bool opt_given(const struct opt_parser *p, int opt)
+{
+ return p->given & (1ULL << opt);
+}
+
+/*
+ * The value of the option last returned as a number from min to max: 0,
+ * or OPT_USAGE, reported.
+ */
+int opt_u64(const struct opt_parser *p, __u64 min, __u64 max,
+ __u64 *out) __must_check;
+
+/* A usage error the command finds, as "<command>: <message>": OPT_USAGE. */
+int opt_usage(const struct opt_parser *p, const char *fmt, ...)
+ __printf(2, 3);
+
+#endif /* SHIRUDO_OPTIONS_H */