/* Copyright © Triad National Security, LLC, and others. */

#define _GNU_SOURCE
#include "config.h"

#include <inttypes.h>
#include <string.h>
#include <sys/sysmacros.h>

#include CJSON_H

#include "all.h"


/** Macros **/


/** Types **/

/* Dispatch table row for CDI hook setup. Note that these are not the hook
   functions themselves but rather functions to translate data in the CDI JSON
   blob to something usable by the hooks.

   Implementation note: We could alternately put “args” last, making it a
   “flexible array member”. That would make the field order slightly
   sub-optimal, but more importantly it would make sizeof() return misleading
   results, which seems like a nasty trap waiting for someone. */
#define HOOK_ARG_MAX 3
struct cdi_hook_parse {
   size_t arg_ct;                     // number of arguments to compare
   char *args[HOOK_ARG_MAX];          // matching arguments
   void (*f)(void *, char **args);    // NULL to ignore quietly
};
#define CHP void (*)(void *, char **args)  // to cast in dispatch tables

struct cdi_spec {
   char *kind;
   char *src_path;         // source spec file path
   dev_t src_dev;          // ... device ID
   ino_t src_ino;          // ... inode number
   struct env_var *envs;
   struct bind *binds;
   char **ldconfigs;       // directories to process with ldconfig(8)
};

struct json_dispatch {
   char *name;
   struct json_dispatch *children;
   void (*f)(cJSON *tree, void *state);
};
#define JDF void (*)(cJSON *, void *)  // to cast callbacks in dispatch tables


/** Constants **/

// Block size in bytes for reading JSON files.
const size_t READ_SZ = 16384;

// Guest path containing CDI bind mounts.
const char CDI_BASE[] = "/ch/cdim";


/** Function prototypes (private) **/

char **array_strings_json_to_c(cJSON *jarry, size_t *ct);
void cdi_append(struct cdi_spec **specs, struct cdi_spec *spec);
void cdi_hook_binds_install(struct container *c);
void cdi_hook_ldconfig_install(struct container *c);
char *cdi_hook_to_string(const char *hook_name, char **args);
void cdi_log(struct cdi_spec *spec);
struct cdi_spec *cdi_read(const char *path);
struct cdi_spec *cdi_read_maybe(struct cdi_spec *specs, const char *path);
bool cdi_requested(struct cdi_config *cf, struct cdi_spec *spec);
bool cdi_resid_path_p(const char *id);
void visit(struct json_dispatch actions[], cJSON *tree, void *state);
void visit_dispatch(struct json_dispatch action, cJSON *tree, void *state);

// parser callbacks
void cdiPC_cdiVersion(cJSON *tree, struct cdi_spec *spec);
void cdiPC_env(cJSON *tree, struct cdi_spec *spec);
void cdiPC_hook(cJSON *tree, struct cdi_spec *spec);
void cdiPC_mount(cJSON *tree, struct cdi_spec *spec);
void cdiPC_kind(cJSON *tree, struct cdi_spec *spec);


/** Globals **/

/* List of CDI specs requested (notably *not* all the specs we could find).

   Yes it’s a global, but that lets us keep struct cdi_spec private to this
   file, which seemed like the right trade-off. It also seemed like “all the
   specs wanted” wasn’t something we needed multiple of. */
struct cdi_spec *cdi_specs = NULL;

/* Callback tables. In the struct, the callback’s second argument is “void *”
   so any state object can be provided. However, we’d prefer the actual
   functions to take the correct pointer type; thus, they need to be cast.
   Alternatives include:

     1. Cast every use of the variable in the callbacks. This seemed verbose
        and error-prone.

     2. Add a local variable of the correct type to each callback. I thought
        such distributed boilerplate seemed worse. */
struct json_dispatch cdiPD_containerEdits[] = {
   { "env",            NULL, (JDF)cdiPC_env },
   { "hooks",          NULL, (JDF)cdiPC_hook },
   { "mounts",         NULL, (JDF)cdiPC_mount },
   { }
};
struct json_dispatch cdiPD_root[] = {
   { "cdiVersion",     NULL, (JDF)cdiPC_cdiVersion },
   { "kind",           NULL, (JDF)cdiPC_kind },
   { "containerEdits", cdiPD_containerEdits, },
   { }
};

/* CDI hook dispatch table. */
struct cdi_hook_parse cdi_hooks[] = {
   // The guest ld cache is automatically updated with the parent directory of
   // bind destinations for shared object libraries.
   { 2, { "nvidia-cdi-hook",    "update-ldcache" },  NULL },
   { 3, { "nvidia-ctk", "hook", "update-ldcache" },  NULL },
   // chmod(1) not needed in unprivileged containers; also this is an obsolete
   // workaround for a runc(1) bug [1].
   // [1]: https://gitlab.com/charliecloud/charliecloud/-/merge_requests/1902#note_2337159332
   { 2, { "nvidia-cdi-hook",    "chmod" },           NULL },
   { 3, { "nvidia-ctk", "hook", "chmod" },           NULL },
   // We bind in the host’s complete /dev, which should already contain any
   // needed symlinks.
   { 2, { "nvidia-cdi-hook",    "create-symlinks" }, NULL },
   { 3, { "nvidia-ctk", "hook", "create-symlinks" }, NULL },
   // “CUDA Forward Compatibility”. See man page.
   { 2, { "nvidia-cdi-hook",    "enable-cuda-compat" }, NULL },
   { 3, { "nvidia-ctk", "hook", "enable-cuda-compat" }, NULL },
   // Apparently nVidia drivers when loaded sometimes *create device nodes* in
   // /dev and thus there is a CDI hook to disable that. See:
   // https://github.com/NVIDIA/nvidia-container-toolkit/pull/927
   { 2, { "nvidia-cdi-hook",    "disable-device-node-modification" }, NULL },
   { 3, { "nvidia-ctk", "hook", "disable-device-node-modification" }, NULL },
   { }
};


/** Functions **/


/* Given JSON array of strings jar, which may be of length zero, convert it to
   a freshly allocated NULL-terminated array of C strings (pointers to
   null-terminated chars buffers) and return that. ct is an out parameter

   WARNING: This is a shallow copy, i.e., the actual strings are still shared
   with the JSON array. */
char **array_strings_json_to_c(cJSON *jarry, size_t *ct)
{
   size_t i;
   char **carry;
   cJSON *j;

   Tf_ (cJSON_IsArray(jarry), "JSON: expected array");
   *ct = cJSON_GetArraySize(jarry);
   carry = malloc_ch((*ct + 1) * sizeof(char *), true);
   carry[*ct] = NULL;

   i = 0;
   cJSON_ArrayForEach(j, jarry) {
      Tf_ (cJSON_IsString(j), "JSON: expected string");
      carry[i++] = j->valuestring;
   }

   return carry;
}

/* Return a list of environment variables to be set for resource id, which can
   be either a resource kind or a path, or if id is NULL, all known devices. */
struct env_var *cdi_envs_get(const char *id)
{
   struct env_var *vars = list_new(0, sizeof(struct env_var));

   for (int i = 0; cdi_specs[i].kind != NULL; i++) {
      // Compare id with both kind and path without checking what it is
      // because it seemed the odds of false positive low enough.
      if (   id == NULL
          || streq(id, cdi_specs[i].kind)
          || streq(id, cdi_specs[i].src_path))
         list_cat((void **)&vars, cdi_specs[i].envs, sizeof(vars[0]));
   }

   return vars;
}

/** Host hook to bind-mount as specified in @p d, which is an array of @c
    struct bind.

    Implementation notes: The CDI specification assumes that each bind-mount
    will be done individually. This seemed like way too many to me -- e.g.,
    one of our not-that-large systems has 47 mounts in the JSON spec file.
    Presently, we bind-mount the *parent directory* of each binding source
    into a subdirectory of @c /ch and symlink the destination into that mount.
    This reduces our 47 mounts to 12 and is simple to implement. It does add
    unnecessary sibling files to the container, notably including shared
    libraries, but these will be out of the way and should not affect any
    containerized applications.

    Alternatives include:

      1. Bind each specified mount individually. As noted, this clutters the
         mount list.

      2. Bind the entire host filesystem tree to a subdirectory of @c /ch and
         symlink. This would also clutter the mount list. Another disadvantage
         is the creation of directory loops (because the image is mounted on
         the host) unless we used the overlayfs to white out the parts of this
         tree we didn’t want.

      3. Bind each filesystem found in the source list once non-recursively
         and symlink. This would provide the minimum number of binds but is
         harder to implement, and it would also benefit from white-outs to
         reduce the number of files in the directory tree.

    @note
    If a bind target exists, it is moved to a hidden name and replaced with a
    symlink, to emulate over-mounting. We move instead of deleting in case the
    target is a non-empty directory. */
void cdi_hook_binds(struct container *c, void *d)
{
   struct bind *binds = d;
   char *cdi_base_host = path_join(c->newroot, CDI_BASE);
   T__ (binds != NULL);

   DEBUG("CDI: merge-bind scratch: %s", cdi_base_host);
   if (mkdir(cdi_base_host, 0777)) {
      // OK if the directory exists, but other errors are a problem.
      Tfe (errno == EEXIST, "can't mkdir: %s", cdi_base_host);
   }

   for (int i = 0; binds[i].src != NULL; i++) {
      DEBUG("CDI: merge-bind: %s -> %s", binds[i].src, binds[i].dst);
      bind_mount(binds[i].src, binds[i].dst, c->newroot,
                 BD_DST_CREATE|BD_DST_MERGE, CDI_BASE);
   }
}

/** Install into @p c a host hook that bind-mounts the files and directories
    needed by the requested CDI specs. If there are no such binds, install no
    hook.

    @note We have a single hook that does all the binding, regardless of the
    number of specs. */
void cdi_hook_binds_install(struct container *c)
{
   struct bind *binds = NULL;

   // note that we de-dup later, in the hook
   for (int i = 0; cdi_specs[i].kind != NULL; i++)
      list_cat((void **)&binds, cdi_specs[i].binds, sizeof(binds[0]));

   if (binds != NULL)
      hook_add(&c->hooks_host, HOOK_DUP_FAIL,
               "cdi-bind", cdi_hook_binds, binds);
}

/** Guest hook to @c ldconfig(8) the specified directories. If no
    @c ldconfig(8) found in the image, exit with error. We try @c $PATH,
    @c /sbin/ldconfig, and @c /usr/sbin/ldconfig in that order. */
void cdi_hook_ldconfig(struct container *c, void *d)
{
   char **ldconfigs = d;

   T__ (ldconfigs != NULL);
   // ldconfig(8) is *very* verbose, so only give it “-v” under our “-vvv”.
   run_wait("ldconfig", "/sbin:/usr/sbin", ldconfigs,
            (verbose >= LL_TRACE ? "-v" : NULL), NULL);
}

/** Install a guest hook that runs @c ldconfig(8) on the directories the
    requested CDI specs wanted. If there are none, do nothing, i.e., install
    no hook rather than a hook that processes no directories.

    @note We have a single hook that runs @c ldconfig(8) at most once
    regardless of the number of specs. */
void cdi_hook_ldconfig_install(struct container *c)
{
   char **ldconfigs = NULL;

   for (int i = 0; cdi_specs[i].kind != NULL; i++)
      list_cat((void **)&ldconfigs, cdi_specs[i].ldconfigs, sizeof(char *));
   list_dedup_strings(ldconfigs);

   if (ldconfigs != NULL)
      hook_add(&c->hooks_guest, HOOK_DUP_FAIL,
               "cdi-ldconfig", cdi_hook_ldconfig, ldconfigs);
}

/* Return a freshly allocated string describing the given hook, for logging. */
char *cdi_hook_to_string(const char *hook_name, char **args)
{
   char *args_str;

   args_str = "";
   for (size_t i = 0; args[i] != NULL; i++)
      args_str = cats(3, args_str, " ", args[i]);

   return asprintf_ch("%s:%s", hook_name, args_str);
}

/** Install the CDI hooks.

    @param c  Container description to modify. */
void cdi_hooks_install(struct container *c)
{
   cdi_hook_binds_install(c);
   cdi_hook_ldconfig_install(c);
}

/* Read the CDI spec files needed, and initialize cdi_specs to contain the
   requested specs.

   Note: We only read spec files in the search path directories if either
   (a) --cdi is specified with no argument, requesting all known devices or
   (b) a device kind (rather than a filename) is given to --cdi (e.g.,
   “nvidia.com/gpu”. This protects users from errors in the spec files if they
   have not requested any CDI features. */
void cdi_init(struct cdi_config *cf)
{
   bool req_by_kind = false;
   size_t spec_ct;

   // Initialize specs list.
   T__ (cdi_specs == NULL);
   cdi_specs = list_new(0, sizeof(struct cdi_spec));

   // Read CDI spec files requested by path. This loop will error out if any
   // files are malformed or not found, i.e., when this loop is done, we know
   // any files given with --cdi are present and valid.
   for (int i = 0; cf->ids[i] != NULL; i++)
      if (cdi_resid_path_p(cf->ids[i])) {
         struct cdi_spec *spec = cdi_read_maybe(cdi_specs, cf->ids[i]);
         if (spec != NULL)
            list_append((void **)&cdi_specs, spec, sizeof(*spec));
      } else
         req_by_kind = true;

   // If the user requested all CDI (--cdi with no argument) or CDI by kind
   // (--cdi=foo/bar), read all spec files we can find. If we get past this
   // block, we found at least one spec file containing what we wanted.
   if (cf->res_all_p || req_by_kind) {
      size_t dir_ct = 0;
      size_t file_ct = 0;
      for (int i = 0; cf->spec_dirs[i] != NULL; i++) {
         char **entries;
         if (path_exists(cf->spec_dirs[i], NULL, true)) {
            VERBOSE("CDI: looking for resource files in: %s", cf->spec_dirs[i]);
            dir_ct++;
         } else {
            VERBOSE("CDI: directory not found, skipping: %s", cf->spec_dirs[i]);
            continue;
         }
         entries = dir_glob(cf->spec_dirs[i], "*.json");
         for (int j = 0; entries[j] != NULL; j++) {
            struct cdi_spec *spec;
            spec = cdi_read_maybe(cdi_specs,
                                  path_join(cf->spec_dirs[i], entries[j]));
            if (spec != NULL) {
               file_ct++;
               if (cdi_requested(cf, spec))
                  list_append((void **)&cdi_specs, spec, sizeof(*spec));
            }
         }
      }
      if (dir_ct == 0)
         FATAL(-1, "CDI: no directories found: %s",
               list_stringify(cf->spec_dirs, ':'));
      if (file_ct == 0)
         FATAL(-1, "CDI: no resource files found: %s",
                   list_stringify(cf->spec_dirs, ':'));
   }

   // Log parsed CDI specs and validate count.
   spec_ct = list_count(cdi_specs, sizeof(cdi_specs[0]));
   DEBUG("CDI: read %zu specs", spec_ct);
   if (spec_ct == 0) {
      if (req_by_kind)
         FATAL(-1, "CDI: no matching resources found");
      else {
         // Nothing to do, and we did nothing.
         T__ (cf->ids[0] == NULL && !cf->res_all_p);
      }
   }
   for (size_t i = 0; i < spec_ct; i++)
      cdi_log(&cdi_specs[i]);
}

/* Log contents of spec. */
void cdi_log(struct cdi_spec *spec)
{
   size_t ct;

   // Use inttypes and cast uintmax_t to avoid error on warning for 32-bit
   // systems.
   DEBUG("CDI: %s from %s (%u,%u %ju):", spec->kind, spec->src_path,
         major(spec->src_dev), minor(spec->src_dev), (uintmax_t)spec->src_ino);

   ct = list_count((void *)(spec->envs), sizeof(struct env_var));
   DEBUG("CDI:   environment: %zu:", ct);
   for (size_t i = 0; i < ct; i++)
      DEBUG("CDI:     %s=%s", spec->envs[i].name, spec->envs[i].value);
   ct = list_count((void *)(spec->binds), sizeof(struct bind));
   DEBUG("CDI:   bind mounts: %zu:", ct);
   for (size_t i = 0; i < ct; i++)
      DEBUG("CDI:     %s ->  %s", spec->binds[i].src, spec->binds[i].dst);
   ct = list_count((void *)(spec->ldconfigs), sizeof(char *));
   DEBUG("CDI:   ldconfig directories: %zu:", ct);
   for (size_t i = 0; i < ct; i++)
      DEBUG("CDI:     %s", spec->ldconfigs[i]);
}

/* Read and parse the CDI spec file at path. Return a pointer to the parsed
   struct. If something goes wrong, exit with error. */
struct cdi_spec *cdi_read(const char *path)
{
   FILE *fp;
   struct stat st;
   char *text;
   const char *parse_end;
   cJSON *tree;
   struct cdi_spec *spec = NULL;

   // Read file into string. Allocate incrementally rather than seeking so
   // non-seekable input works.
   Tfe (fp = fopen(path, "rb"), "CDI: can't open: %s", path);
   Zfe (fstat(fileno(fp), &st), "CDI: can't stat: %s", path);
   text = NULL;
   for (size_t used = 0, avail = READ_SZ; true; avail += READ_SZ) {
      size_t read_ct;
      text = realloc_ch(text, avail, false);
      read_ct = fread(text + used, 1, READ_SZ, fp);
      used += read_ct;
      if (read_ct < READ_SZ) {
         Tfe (feof(fp), "CDI: can't read: %s", path);
         T__ (used < avail);
         text[used] = '\0';  // terminate string
         break;
      }
   }

   // Parse JSON.
   tree = cJSON_ParseWithOpts(text, &parse_end, false);
   Tf_ (tree != NULL,
        "CDI: JSON failed at byte %zd: %s", parse_end - text, path);

   // Visit parse tree to build our struct.
   spec = malloc_ch(sizeof(struct cdi_spec), true);
   spec->src_path = (char *)path;  // shouldn’t ever be written
   spec->src_dev = st.st_dev;
   spec->src_ino = st.st_ino;
   spec->envs = NULL;
   spec->binds = NULL;
   spec->ldconfigs = NULL;
   visit(cdiPD_root, tree, spec);

   // Clean up.
   VERBOSE("CDI: spec read OK: %s: %s", spec->kind, path);
   return spec;
}

/* Read and parse the CDI spec file at path, returning a pointer to the
   newly-allocated spec struct, unless (1) we already read the file, in which
   case log that fact and return NULL, or (2) the device kind has already been
   specified, in which case exit with error. If something else goes wrong,
   also exit with error. */
struct cdi_spec *cdi_read_maybe(struct cdi_spec *specs, const char *path)
{
   struct cdi_spec *spec;
   struct stat st;

   // Don’t read file if we already did. It’s relatively easy to give a spec
   // file more than once, e.g. if it’s in the search path and also an
   // argument to --device.
   Zfe (stat(path, &st), "can't stat CDI resource file: %s", path);
   for (int i = 0; specs[i].kind != NULL; i++) {
      if (st.st_dev == specs[i].src_dev && st.st_ino == specs[i].src_ino) {
         VERBOSE("CDI: spec already read, skipping: %s", path);
         return NULL;
      }
   }

   spec = cdi_read(path);

   // Error if this device already specified, which because we don’t re-read
   // files means two files specified the same device kind.
   for (int i = 0; specs[i].kind != NULL; i++)
      Zf_ (streq(spec->kind, specs[i].kind),
           "CDI: device found in multiple spec files: %s: %s and %s",
           spec->kind, specs[i].src_path, spec->src_path);

   return spec;
}

/* Return true if the given spec was requested by configuration cf, false
   otherwise. */
bool cdi_requested(struct cdi_config *cf, struct cdi_spec *spec)
{
   if (cf->res_all_p)
      return true;

   for (int i = 0; cf->ids[i] != NULL; i++)
      if (   !cdi_resid_path_p(cf->ids[i])
          && streq(cf->ids[i], spec->kind))
         return true;

   return false;
}

/** Validate and canonicalize a CDI resource identifier. If validation fails,
    exit with an error message.

    @param id  Device kind or path, as specified in the man page.

    @returns Validated, canonical form of @p d. This is a newly allocated
    string even if no changes were needed.

    @note
    Validation does not fully address the requirements in the standard [1] but
    rather only what we specifically need.

    [1]: https://github.com/cncf-tags/container-device-interface/blob/v1.0.1/SPEC.md#kind */
char *cdi_resid_canonicalize(const char *id)
{
   char *dnew;

   T__ (id != NULL);
   Tf_ (strlen(id) > 0, "CDI: empty resource ID");

   if (cdi_resid_path_p(id))    // path, nothing more to do
      dnew = strdup_ch(id);
   else {                          // device kind, e.g. “nvidia.com/gpu=all”
      char *kpre;   // e.g. “nvidia.com”
      char *kname;  // e.g. “gpu”
      char *dname;  // e.g. “all”
      split(&kpre, &kname, id, '/');
      split(&kname, &dname, kname, '=');
      Tf_ (!strchr(kname, '/'), "CDI: resource kind with multiple slashes");
      if (dname && streq(dname, "all")) {
         DEBUG("ignoring no-op resource name \"=all\"");
         dname = NULL;
      }
      Tf_ (!dname, "CDI: resource names not accepted: %s", dname);
      dnew = path_join(kpre, kname);
   }

   return dnew;
}

/** Guess if a CDI resource ID is a path or resource kind. See man page for
    the heuristic.

    @param id  Resource ID to evaluate. May not be @c NULL or an empty string.

    @returns True if @p id seems more likely a path, false if more likely a
    resource kind. */
bool cdi_resid_path_p(const char *id)
{
   const char *ext;

   T__ (id != NULL && id[0] != '\0');
   ext = strrchr(id, '.');
   return (ext && streq(ext, ".json"));
}

char **cdi_spec_dirs_default()
{
   char *dirs = getenv("CH_RUN_CDI_DIRS");
   if (!dirs)
      dirs = "/etc/cdi:/var/run/cdi";
   return list_new_strings(':', dirs);
}

void cdiPC_cdiVersion(cJSON *tree, struct cdi_spec *spec)
{
   DEBUG("CDI: %s: version %s", spec->src_path, tree->valuestring);
}

void cdiPC_env(cJSON *tree, struct cdi_spec *spec)
{
   struct env_var ev;
   size_t name_len, value_len;  // not including null terminator
   char *delim, *arnold;

   T__ (cJSON_IsString(tree));
   T__ (delim = strchr(tree->valuestring, '='));
   T__ (arnold = strchr(tree->valuestring, 0));

   name_len = delim - tree->valuestring;
   value_len = arnold - delim - 1;
   ev.name = malloc_ch(name_len + 1, false);
   memcpy(ev.name, tree->valuestring, name_len);
   ev.name[name_len] = 0;
   ev.value = malloc_ch(value_len + 1, false);
   memcpy(ev.value, delim + 1, value_len);
   ev.value[value_len] = 0;

   list_append((void **)&spec->envs, &ev, sizeof(ev));
}

void cdiPC_hook(cJSON *tree, struct cdi_spec *spec)
{
   char **args;
   size_t arg_ct;
   char *hook_name;
   char *hook_str;
   bool hook_known;

   T__ (hook_name = cJSON_GetStringValue(cJSON_GetObjectItem(tree,
                                                             "hookName")));

   T__ (cJSON_IsArray(cJSON_GetObjectItem(tree, "args")));
   args = array_strings_json_to_c(cJSON_GetObjectItem(tree, "args"), &arg_ct);
   hook_str = cdi_hook_to_string(hook_name, args);

   hook_known = false;
   for (size_t i = 0; cdi_hooks[i].arg_ct != 0; i++) {  // for each table row
      if (arg_ct >= cdi_hooks[i].arg_ct) {   // enough hook args to compare
         for (size_t j = 0; j < cdi_hooks[i].arg_ct; j++)
            if (!streq(args[j], cdi_hooks[i].args[j]))
                goto continue_outer;
         hook_known = true;  // all words matched
         if (cdi_hooks[i].f == NULL) {
            DEBUG("CDI: ignoring known hook: %s", hook_str);
         } else {
            DEBUG("CDI: emulating known hook: %s", hook_str);
            cdi_hooks[i].f(spec, &args[cdi_hooks[i].arg_ct]);
         }
         break;  // only call one hook function
      }
   continue_outer:
      ;
   }

   if (!hook_known)
      WARNING("CDI: ignoring unknown hook: %s", hook_str);
}

void cdiPC_kind(cJSON *tree, struct cdi_spec *spec)
{
   T__ (spec->kind = strdup_ch(tree->valuestring));
}

void cdiPC_mount(cJSON *tree, struct cdi_spec *spec)
{
   char *ph, *pg;
   char *src_dirname = NULL;
   bool bind_p;
   cJSON *j, *opts;
   struct bind bind;

   // host and guest paths (both required)
   T__ (ph = cJSON_GetStringValue(cJSON_GetObjectItem(tree, "hostPath")));
   T__ (pg = cJSON_GetStringValue(cJSON_GetObjectItem(tree, "containerPath")));

   // validate that it’s a bind mount
   opts = cJSON_GetObjectItem(tree, "options");
   if (!opts)
      bind_p = false;
   else {
      T__ (cJSON_IsArray(opts));
      bind_p = false;
      cJSON_ArrayForEach(j, opts) {
         T__ (cJSON_IsString(j));
         if (streq(j->valuestring, "bind") || streq(j->valuestring, "rbind")) {
            bind_p = true;
            break;
         }
      }
   }
   if (!bind_p) {
      WARNING("CDI: ignoring non-bind mount: %s -> %s", ph, pg);
      return;
   }

   // save in spec
   bind.src = path_tidy(ph);
   if (bind.src[0] != '/') {
      char *src_abs = path_absolve(bind.src, spec->src_path, true);
      DEBUG("absolved relative bind source: %s -> %s", bind.src, src_abs);
      bind.src = src_abs;
   }
   T__ (bind.src[0] == '/');
   bind.dst = path_tidy(pg);
   Tf_ (bind.dst[0] == '/',
        "CDI: can't bind relative guest path: %s", bind.dst);
   bind.flags = 0;
   list_append((void **)&spec->binds, &bind, sizeof(bind));

   // Add shared object library parent directory to list of ldconfig targets.
   // We use pattern comparision on the path name, rather than helper functions
   // from elf.h, because 1) it is simple, and 2) it is unclear if libc
   // development headers are reliably available.
   bind.src = realpath_ch(bind.src); // absolute path, let ldconfig make links
   if (path_is_shared_object(bind.src)) {
      src_dirname = dirname_ch(bind.src);
      T__ (src_dirname != NULL && src_dirname[0] == '/');
      list_append((void **)&spec->ldconfigs, &src_dirname, sizeof(src_dirname));
   }
}

/* Initialize the cJSON stuff. Quirks:

   1. Despite using reallocation internally, cJSON indeed does not accept a
      realloc(3) replacement, though it possibly used to. If malloc(3) and
      free(3) are provided, then it just doesn’t call any realloc().

      Weirdly, cJSON appears to have a notion of “internal” memory management
      that uses malloc(3), realloc(3), and free(3) regardless of these hooks.

   2. cJSON prefixes everything with CJSON_CDECL, which is just __cdecl, which
      is unnecessary for C code. Maybe this is for using cJSON in C++? */
void json_init(void)
{
   cJSON_Hooks hooks = (cJSON_Hooks) {
      .malloc_fn = malloc_pointerful,
      .free_fn = free_ch,
   };

   cJSON_InitHooks(&hooks);
}

/* Visit each node in the parse tree in depth-first order. At each node, if
   there is a matching callback in actions, call it. For arrays, call the
   callback once per array element. */
void visit(struct json_dispatch actions[], cJSON *tree, void *state)
{
   for (int i = 0; actions[i].name != NULL; i++) {
      cJSON *subtree = cJSON_GetObjectItem(tree, actions[i].name);
      if (subtree != NULL) {  // child matching action name exists
         if (!cJSON_IsArray(subtree))
            visit_dispatch(actions[i], subtree, state);
         else {
            cJSON *elem;
            cJSON_ArrayForEach(elem, subtree)
               visit_dispatch(actions[i], elem, state);
         }
      }
   }
}

/* Call the appropriate callback for the the root node of tree, if any. Then
   visit its children, if any. */
void visit_dispatch(struct json_dispatch action, cJSON *tree, void *state)
{
   if (action.f != NULL)
      action.f(tree, state);
   if (action.children != NULL)
      visit(action.children, tree, state);
}
