File: json.c

package info (click to toggle)
charliecloud 0.43-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,116 kB
  • sloc: python: 6,021; sh: 4,284; ansic: 3,863; makefile: 598
file content (766 lines) | stat: -rw-r--r-- 26,601 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
/* 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_ldconfig_parse(struct cdi_spec *spec, 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[] = {
   { 2, { "nvidia-cdi-hook",    "update-ldcache" },  (CHP)cdi_ldconfig_parse },
   { 3, { "nvidia-ctk", "hook", "update-ldcache" },  (CHP)cdi_ldconfig_parse },
   // 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 },
   { }
};


/** 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);
}

/** Append @c ldconfig(8) directories in @p args to CDI spec @p spec.

    @param spec CDI spec to modify.

    @param args Command line arguments in <tt>nvidia-ctk-hook
                update-ldcache</tt> syntax.

    For example:

    @code{.sh}
    nvidia-ctk-hook update-ldcache --folder /foo --folder /bar
    @endcode

    would result in the directories @c /foo and @c bar being added to the spec
    structure.

    Can be called multiple times, though I don’t think that is tested. */
void cdi_ldconfig_parse(struct cdi_spec *spec, char **args)
{
   for (int i = 0; args[i] != NULL; i++)
      if (streq(args[i], "--folder")) {
         i++;
         Tf_ ((args[i] != NULL && args[i][0] != '\0'),
              "CDI: nvidia-ctk-hook: --folder: missing argument");
         list_append((void **)&spec->ldconfigs, &args[i], sizeof(args[i]));
      } else
         FATAL(-1, "CDI: nvidia-ctk-hook: invalid argument: %s", args[i]);
}

/* 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;
   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")) {
            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));
}

/* 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);
}