]> git.tuebingen.mpg.de Git - lopsub.git/blob - lopsub.c
Improve error message of lls_check_arg_count().
[lopsub.git] / lopsub.c
1 /*
2  * Copyright (C) 2016 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the LGPL v3, see http://www.gnu.org/licenses/lgpl-3.0.html
5  */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <stdbool.h>
10 #include <assert.h>
11 #include <stdarg.h>
12 #include <inttypes.h>
13 #include <errno.h>
14 #include <limits.h>
15
16 #include "lopsub-internal.h"
17 #include "lopsub.h"
18
19 /* For detecting version mismatches, see lopsub-internal.h. */
20 const unsigned LLS_ABI_VERSION_VAR = 0;
21
22 #define FOR_EACH_OPTION(_i, _opts) \
23         for (_i = 0; (_opts) && (_opts)[(_i)].name; (_i)++)
24
25 #define FOR_EACH_OPTION_IN_COMMAND(_opt, _cmd) \
26         for ( \
27                 (_opt) = (_cmd)->options; \
28                 (_opt) && (_opt) < (_cmd)->options + (_cmd)->num_options; \
29                 (opt)++ \
30         )
31
32 /* The result of parsing one option and its arguments. */
33 struct lls_arg {
34         int idx; /* index into either argv[] or the lls_option array. */
35         const char *arg; /* NULL if option has no argument. */
36 };
37
38 /*
39  * This structure, and the exchange_args(), decode_option() and parse_option()
40  * functions below are inspired by the glibc implementation of getopt.c,
41  * Copyright (C) 1987-2015 Free Software Foundation, Inc.
42  */
43 struct lls_data {
44         const struct lls_option *opts;
45         int argc;
46         char *const *argv;
47
48         int optind; /* index into argv[] which we are parsing. */
49         const char *next_char;
50         /*
51          * These describe the part of argv[] that contains non-options that
52          * have been skipped. first_nonopt is the index in argv[] of the first
53          * of them, last_nonopt is the index after the last of them. Initially
54          * both indices are zero.
55          */
56         int first_nonopt;
57         int last_nonopt;
58 };
59
60 const struct lls_command *lls_cmd(unsigned cmd_num,
61                 const struct lls_suite *suite)
62 {
63         if (cmd_num > suite->num_subcommands)
64                 return NULL;
65         return suite->commands + cmd_num;
66 }
67
68 const char *lls_command_name(const struct lls_command *cmd)
69 {
70         return cmd->name;
71 }
72
73 const void *lls_user_data(const struct lls_command *cmd)
74 {
75         return cmd->user_data;
76 }
77
78 const struct lls_option *lls_opt(unsigned opt_num,
79                 const struct lls_command *cmd)
80 {
81         return cmd->options + opt_num;
82 }
83
84 const struct lls_opt_result *lls_opt_result(unsigned opt_num,
85                 const struct lls_parse_result *lpr)
86 {
87         return lpr->opt_result + opt_num;
88 }
89
90 unsigned lls_opt_given(const struct lls_opt_result *r)
91 {
92         return r->given;
93 }
94
95 const char *lls_enum_string_val(unsigned idx, const struct lls_option *opt)
96 {
97         return opt->values[idx].string_val;
98 }
99
100 const char *lls_string_val(unsigned idx, const struct lls_opt_result *r)
101 {
102         return r->value[idx].string_val;
103 }
104
105 int32_t lls_int32_val(unsigned idx, const struct lls_opt_result *r)
106 {
107         return r->value[idx].int32_val;
108 }
109
110 uint32_t lls_uint32_val(unsigned idx, const struct lls_opt_result *r)
111 {
112         return r->value[idx].uint32_val;
113 }
114
115 int64_t lls_int64_val(unsigned idx, const struct lls_opt_result *r)
116 {
117         return r->value[idx].int64_val;
118 }
119
120 uint64_t lls_uint64_val(unsigned idx, const struct lls_opt_result *r)
121 {
122         return r->value[idx].uint64_val;
123 }
124
125 unsigned lls_num_inputs(const struct lls_parse_result *lpr)
126 {
127         return lpr->num_inputs;
128 }
129
130 const char *lls_purpose(const struct lls_command *cmd)
131 {
132         return cmd->purpose;
133 }
134
135 const char *lls_input(unsigned input_num, const struct lls_parse_result *lpr)
136 {
137         return lpr->inputs[input_num];
138 }
139
140 const char *lls_strerror(int lss_errno)
141 {
142         #define LLS_ERROR(_n, _s) _s,
143         static const char * const error_string[] = {LLS_ERRORS NULL};
144         #undef LLS_ERROR
145         return error_string[lss_errno];
146 }
147
148 static int xrealloc(void *p, size_t size)
149 {
150         void **pp = p, *newp = realloc(*pp, size);
151
152         if (!newp)
153                 return -E_LLS_NOMEM;
154         *pp = newp;
155         return 0;
156 }
157
158 /* Print a formatted message to a dynamically allocated string. */
159 __attribute__ ((format (printf, 2, 0)))
160 static int xvasprintf(char **result, const char *fmt, va_list ap)
161 {
162         int ret;
163         size_t size = 150;
164         va_list aq;
165
166         if (!result)
167                 return 0;
168         if (*result)
169                 free(*result);
170         *result = malloc(size + 1);
171         if (!*result)
172                 return -E_LLS_NOMEM;
173         va_copy(aq, ap);
174         ret = vsnprintf(*result, size, fmt, aq);
175         va_end(aq);
176         assert(ret >= 0);
177         if (ret < size) /* OK */
178                 return ret;
179         size = ret + 1;
180         ret = xrealloc(result, size);
181         if (ret < 0) {
182                 free(*result);
183                 *result = NULL;
184                 return ret;
185         }
186         va_copy(aq, ap);
187         ret = vsnprintf(*result, size, fmt, aq);
188         va_end(aq);
189         assert(ret >= 0 && ret < size);
190         return ret;
191 }
192
193 /* Print to a dynamically allocated string, variable number of arguments. */
194 __attribute__ ((format (printf, 2, 3)))
195 static int xasprintf(char **result, const char *fmt, ...)
196 {
197         va_list ap;
198         unsigned ret;
199
200         va_start(ap, fmt);
201         ret = xvasprintf(result, fmt, ap);
202         va_end(ap);
203         return ret;
204 }
205
206 static inline unsigned num_vals_in_parse_result(const struct lls_command *cmd,
207         int opt_num, const struct lls_parse_result *lpr)
208 {
209         const struct lls_option *opt = cmd->options + opt_num;
210         struct lls_opt_result *lor = lpr->opt_result + opt_num;
211
212         if (opt->arg_info == LLS_NO_ARGUMENT)
213                 return 0;
214         if (lor->given == 0)
215                 return 1; /* for the default value */
216         if (!(opt->flags & LLS_MULTIPLE))
217                 return 1;
218         return lor->given;
219 }
220
221 union atoi_result {
222         int32_t int32;
223         uint32_t uint32;
224         int64_t int64;
225         uint64_t uint64;
226 };
227
228 enum atoi_mode {ATOI_INT32, ATOI_UINT32, ATOI_INT64, ATOI_UINT64};
229
230 /*
231  * Convert a string to a 32 or 64 bit signed or unsigned integer value.
232  *
233  * For conversions to unsigned integers, negative values are considered valid
234  * input and are silently converted.
235  */
236 static int lls_atoi(const char *str, enum atoi_mode mode, union atoi_result *value)
237 {
238         char *endptr;
239         union atoi_result result;
240
241         memset(value, 0, sizeof(*value));
242         errno = 0; /* To distinguish success/failure after call */
243         /*
244          * We pass zero as the base to strtoll(3) and strtoull(3) to let the
245          * function recognize an optional base prefix like "0x".
246          */
247         if (mode == ATOI_UINT64) {
248                 unsigned long long tmp = strtoull(str, &endptr, 0);
249                 if (errno == ERANGE && tmp == ULLONG_MAX)
250                         return -E_LLS_OVERFLOW;
251                 result.uint64 = tmp;
252         } else { /* parse as signed 64 bit and check range */
253                 long long tmp = strtoll(str, &endptr, 0);
254                 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
255                         return -E_LLS_OVERFLOW;
256                 switch (mode) {
257                 case ATOI_INT64: /* no additional range check necessary */
258                         result.int64 = tmp;
259                         break;
260                 case ATOI_INT32:
261                         if (tmp < INT_MIN || tmp > INT_MAX)
262                                 return -E_LLS_OVERFLOW;
263                         result.int32 = tmp;
264                         break;
265                 case ATOI_UINT32:
266                         if (tmp > UINT_MAX)
267                                 return -E_LLS_OVERFLOW;
268                         result.uint32 = tmp;
269                         break;
270                 default:
271                         assert(0);
272                 }
273         }
274         /*
275          * If there were no digits at all, strtol() and friends store the
276          * original value of str in *endptr.
277          */
278         if (endptr == str)
279                 return -E_LLS_NO_DIGITS;
280         /*
281          * The implementation may also set errno (and return 0) in case no
282          * conversion was performed.
283          */
284         if (errno != 0)
285                 return -E_LLS_NO_DIGITS;
286         if (*endptr != '\0') /* Further characters after number */
287                 return -E_LLS_TRAILING_GARBAGE;
288         *value = result;
289         return 1;
290 }
291
292 static int atoi32(const char *str, int32_t *result)
293 {
294         union atoi_result ar;
295         int ret = lls_atoi(str, ATOI_INT32, &ar);
296         *result = ar.int32;
297         return ret;
298 }
299
300 static int atou32(const char *str, uint32_t *result)
301 {
302         union atoi_result ar;
303         int ret = lls_atoi(str, ATOI_UINT32, &ar);
304         *result = ar.uint32;
305         return ret;
306 }
307
308 static int atoi64(const char *str, int64_t *result)
309 {
310         union atoi_result ar;
311         int ret = lls_atoi(str, ATOI_INT64, &ar);
312         *result = ar.int64;
313         return ret;
314 }
315
316 static int atou64(const char *str, uint64_t *result)
317 {
318         union atoi_result ar;
319         int ret = lls_atoi(str, ATOI_UINT64, &ar);
320         *result = ar.uint64;
321         return ret;
322 }
323
324 static void free_opt_result(int opt_num, struct lls_parse_result *lpr,
325                 const struct lls_command *cmd)
326 {
327         const struct lls_option *opt = cmd->options + opt_num;
328
329         if (opt->arg_type == LLS_STRING && !opt->values) {
330                 unsigned num_vals = num_vals_in_parse_result(cmd, opt_num, lpr);
331                 int j;
332                 for (j = 0; j < num_vals; j++)
333                         if (lpr->opt_result[opt_num].value)
334                                 free(lpr->opt_result[opt_num].value[j].string_val);
335         }
336         if (opt->arg_info != LLS_NO_ARGUMENT)
337                 free(lpr->opt_result[opt_num].value);
338 }
339
340 void lls_free_parse_result(struct lls_parse_result *lpr,
341                 const struct lls_command *cmd)
342 {
343         int i;
344
345         if (!lpr)
346                 return;
347         if (lpr->inputs)
348                 for (i = 0; i < lpr->num_inputs; i++)
349                         free(lpr->inputs[i]);
350         free(lpr->inputs);
351         if (lpr->opt_result)
352                 FOR_EACH_OPTION(i, cmd->options)
353                         free_opt_result(i, lpr, cmd);
354         free(lpr->opt_result);
355         free(lpr);
356 }
357
358 static struct lls_data *init_lls_data(const struct lls_option *opts,
359                 int argc, char *const *argv)
360 {
361         struct lls_data *d = malloc(sizeof(*d));
362
363         if (!d)
364                 return NULL;
365         d->optind = 0;
366         /* start with an empty non-option list */
367         d->first_nonopt = d->last_nonopt = d->optind;
368         d->opts = opts;
369         d->argc = argc;
370         d->argv = argv;
371         d->next_char = NULL;
372         return d;
373 }
374
375 /*
376  * Exchange two adjacent subsets of argv[].
377  *
378  * One subset is given by indices {first_nonopt, ..., last_nonopt - 1}. It
379  * contains all the non-options that have been skipped so far. The other subset
380  * corresponds to indices {last_nonopt, ... optind - 1} which contains all the
381  * options processed since those non-options were skipped.
382  *
383  * Before the function returns, ->first_nonopt and ->last_nonopt are updated to
384  * describe the new set of non-options in argv[].
385  */
386 static void exchange_args(struct lls_data *d)
387 {
388         int bottom = d->first_nonopt;
389         int middle = d->last_nonopt;
390         int top = d->optind;
391         char **argv = (char **)d->argv;
392
393         /*
394          * Exchange the shorter segment with the far end of the longer segment.
395          * That puts the shorter segment into the right place. It leaves the
396          * longer segment in the right place overall, but it consists of two
397          * parts that need to be swapped next.
398         */
399         while (top > middle && middle > bottom) {
400                 if (top - middle > middle - bottom) {
401                         /* Bottom segment is the short one.  */
402                         int i, len = middle - bottom;
403
404                         /* Swap it with the top part of the top segment. */
405                         for (i = 0; i < len; i++) {
406                                 char *tmp = argv[bottom + i];
407                                 argv[bottom + i] = argv[top - (middle - bottom) + i];
408                                 argv[top - (middle - bottom) + i] = tmp;
409                         }
410                         /* Exclude the moved bottom segment from further swapping. */
411                         top -= len;
412                 } else {
413                         /* Top segment is the short one.  */
414                         int i, len = top - middle;
415                         /* Swap it with the bottom part of the bottom segment. */
416                         for (i = 0; i < len; i++) {
417                                 char *tmp = argv[bottom + i];
418                                 argv[bottom + i] = argv[middle + i];
419                                 argv[middle + i] = tmp;
420                         }
421                         /* Exclude the moved top segment from further swapping. */
422                         bottom += len;
423                 }
424         }
425         /* Update records for the slots the non-options now occupy. */
426         d->first_nonopt += d->optind - d->last_nonopt;
427         d->last_nonopt = d->optind;
428 }
429
430 /* whether arg points to an option argument */
431 static inline bool is_option(const char *arg)
432 {
433         return arg[0] == '-' && arg[1] != '\0';
434 }
435
436 static void check_errctx(char **errctx, int ret)
437 {
438         if (!errctx)
439                 return;
440         if (ret >= 0)
441                 assert(!*errctx); /* memory leak/uninitialized pointer */
442         else if (ret != -E_LLS_NOMEM)
443                 assert(*errctx); /* we must provide an error message */
444 }
445
446 /*
447  * Decode the current option. On success, set result->idx to the index in the
448  * ->options array which was decoded successfully. On failure, result->idx is
449  * the index in argv[] which could not be parsed.
450  */
451 static int decode_option(struct lls_data *d, struct lls_arg *result,
452                 char **errctx)
453 {
454         const char *word = d->argv[d->optind], *cur, *end;
455         size_t len;
456         int i;
457         const struct lls_option *match = NULL;
458         bool ambig = false, shortopt;
459
460         assert(word[0] != '\0');
461         shortopt = word[1] != '-';
462         result->idx = d->optind;
463         result->arg = word;
464
465         if (d->next_char)
466                 cur = d->next_char;
467         else
468                 cur = word + 1 + !shortopt; /* skip dash(es) */
469         for (end = cur; *end && *end != '='; end++)
470                 ; /* nothing */
471         len = end - cur;
472
473         /* test all options for exact or abbreviated matches */
474         FOR_EACH_OPTION(i, d->opts) {
475                 const struct lls_option *opt = d->opts + i;
476                 if (opt->flags & LLS_IGNORED)
477                         continue;
478                 if (shortopt) {
479                         if (*cur != opt->short_opt)
480                                 continue;
481                         match = opt;
482                         d->next_char = cur + 1;
483                         if (d->next_char[0] == '\0' || d->next_char[0] == '=')
484                                 d->next_char = NULL;
485                         break;
486                 }
487                 if (strncmp(opt->name, cur, len) != 0)
488                         continue;
489                 if (strlen(opt->name) == len) { /* exact match */
490                         match = opt;
491                         break;
492                 }
493                 if (match) { /* second non-exact match */
494                         ambig = true;
495                         break;
496                 }
497                 /* first non-exact match */
498                 match = opt;
499         }
500         if (!match) { /* option not found */
501                 xasprintf(errctx, "error token: %s", cur);
502                 return -E_LLS_BAD_OPTION;
503         }
504         if (ambig) {
505                 xasprintf(errctx, "%s", word);
506                 return -E_LLS_AMBIG_OPTION;
507         }
508         if (d->next_char) {
509                 if (match->arg_info == LLS_REQUIRED_ARGUMENT) {
510                         xasprintf(errctx, "--%s", match->name);
511                         return -E_LLS_NO_ARG_GIVEN;
512                 }
513                 result->arg = NULL;
514                 goto success;
515         }
516         d->optind++;
517         if (*end == '=') {
518                 if (match->arg_info == LLS_NO_ARGUMENT) {
519                         xasprintf(errctx, "--%s", match->name);
520                         return -E_LLS_ARG_GIVEN;
521                 }
522                 result->arg = end + 1;
523         } else if (match->arg_info == LLS_REQUIRED_ARGUMENT) {
524                 if (d->optind >= d->argc) {
525                         xasprintf(errctx, "--%s", match->name);
526                         return -E_LLS_NO_ARG_GIVEN;
527                 }
528                 result->arg = d->argv[d->optind++];
529         } else
530                 result->arg = NULL;
531 success:
532         result->idx = match - d->opts;
533         return 1;
534 }
535
536 /*
537  * Parse one option, including its argument (if any).
538  *
539  * We permute the contents of ARGV as we scan, so that eventually all the
540  * non-options are at the end. This allows options to be given in any order.
541  *
542  * Returns zero on end-of-argv, negative on errors, one if an option was parsed
543  * successfully. The structure pointed to by result is initialized as follows:
544  *
545  * end-of-args case: ->idx is the index of first non-option in argv[], ->arg is
546  * argv[result->idx].
547  *
548  * error case: ->idx is the index of the first problematic option in argv. ->arg is
549  * argv[result->idx] as in the end-of-args case.
550  *
551  * success case: ->idx is the index into the option array which corresponds to
552  * the option that was parsed successfully, ->arg its argument, or NULL if no
553  * argument was given.
554  *
555  * After this function returned non-positive, it must not be called again.
556  */
557 static int parse_option(struct lls_data *d, struct lls_arg *result, char **errctx)
558 {
559         assert(d->last_nonopt <= d->optind);
560         assert(d->first_nonopt <= d->optind);
561
562         if (d->next_char)
563                 return decode_option(d, result, errctx);
564         /*
565          * If we have just processed some options following some non-options,
566          * exchange them so that the options come first.
567          */
568         if (d->first_nonopt != d->last_nonopt && d->last_nonopt != d->optind)
569                 exchange_args(d);
570         else if (d->last_nonopt != d->optind)
571                 d->first_nonopt = d->optind;
572         /*
573          * Skip any additional non-options and extend the range of non-options
574          * previously skipped.
575          */
576         while (d->optind < d->argc && !is_option(d->argv[d->optind]))
577                 d->optind++;
578         d->last_nonopt = d->optind;
579         /*
580          * The special argument `--' forces an end of option-scanning. We skip
581          * it like a null option, then exchange it with previous non-options as
582          * if it were an option. Then we skip everything else like a non-option.
583          */
584         if (d->optind != d->argc && !strcmp(d->argv[d->optind], "--")) {
585                 d->optind++;
586                 if (d->first_nonopt != d->last_nonopt && d->last_nonopt != d->optind)
587                         exchange_args(d);
588                 else if (d->first_nonopt == d->last_nonopt)
589                         d->first_nonopt = d->optind;
590                 d->last_nonopt = d->argc;
591                 d->optind = d->argc;
592         }
593         /*
594          * If we have done all the argv elements, stop the scan and back over
595          * any non-options that we skipped and permuted.
596          */
597         if (d->optind == d->argc) {
598                 /*
599                  * Set the index to point at the non-options that we
600                  * previously skipped.
601                  */
602                 result->idx = d->first_nonopt;
603                 result->arg = d->argv[result->idx];
604                 return 0;
605         }
606         assert(is_option(d->argv[d->optind]));
607         return decode_option(d, result, errctx);
608 }
609
610 static int check_enum_arg(const char *arg, const struct lls_option *opt,
611                 char **errctx)
612 {
613         int i;
614         char *val;
615
616         for (i = 0; (val = opt->values[i].string_val); i++)
617                 if (!strcmp(arg, val))
618                         return i;
619         xasprintf(errctx, "arg: %s, option: %s", arg, opt->name);
620         return -E_LLS_ENUM;
621 }
622
623 /*
624  * Increase the "given" count and store argument if the option takes one.
625  * Allocates or reallocates the ->value array of struct lls_opt_result in lpr.
626  */
627 static int lls_parse_arg(struct lls_arg *la, const struct lls_option *opts,
628                 struct lls_parse_result *lpr, char **errctx)
629 {
630         const struct lls_option *opt = opts + la->idx;
631         struct lls_opt_result *lor = lpr->opt_result + la->idx;
632         bool multiple;
633         int idx, ret;
634
635         if (!la->arg)
636                 goto success;
637         if (opt->arg_info == LLS_NO_ARGUMENT) {
638                 xasprintf(errctx, "arg: %s, option: %s", la->arg, opt->name);
639                 return -E_LLS_ARG_GIVEN;
640         }
641         multiple = opt->flags & LLS_MULTIPLE;
642         idx = multiple? lor->given : 0;
643         if (lor->given == 0 || multiple) {
644                 ret = xrealloc(&lor->value,
645                         (lor->given + 1) * sizeof(*lor->value));
646                 if (ret < 0) {
647                         xasprintf(errctx, "option value array for --%s",
648                                 opt->name);
649                         return ret;
650                 }
651         }
652         switch (opt->arg_type) {
653         case LLS_STRING:
654                 if (!opt->values && lor->given > 0 && !multiple)
655                         free(lor->value[idx].string_val);
656                 if (opt->values) {
657                         ret = check_enum_arg(la->arg, opt, errctx);
658                         if (ret < 0)
659                                 return ret;
660                         lor->value[idx].uint32_val = ret;
661                 } else {
662                         lor->value[idx].string_val = strdup(la->arg);
663                         if (!lor->value[idx].string_val) {
664                                 xasprintf(errctx, "string value for %s",
665                                         opt->name);
666                                 return -E_LLS_NOMEM;
667                         }
668                 }
669                 break;
670         case LLS_INT32:
671                 ret = atoi32(la->arg, &lor->value[idx].int32_val);
672                 if (ret < 0)
673                         goto atoi_error;
674                 break;
675         case LLS_UINT32:
676                 ret = atou32(la->arg, &lor->value[idx].uint32_val);
677                 if (ret < 0)
678                         goto atoi_error;
679                 break;
680         case LLS_INT64:
681                 ret = atoi64(la->arg, &lor->value[idx].int64_val);
682                 if (ret < 0)
683                         goto atoi_error;
684                 break;
685         case LLS_UINT64:
686                 ret = atou64(la->arg, &lor->value[idx].uint64_val);
687                 if (ret < 0)
688                         goto atoi_error;
689                 break;
690         default:
691                 assert(false);
692         }
693 success:
694         lor->given++;
695         return 1;
696 atoi_error:
697         assert(ret < 0);
698         xasprintf(errctx, "conversion error for argument \"%s\" to option --%s",
699                 la->arg, opt->name);
700         return ret;
701 }
702
703 static int copy_val(union lls_val *dst, const union lls_val *src,
704                 const struct lls_option *opt, char **errctx)
705 {
706         if (opt->arg_type != LLS_STRING || opt->values) {
707                 *dst = *src;
708                 return 0;
709         }
710         if (!src->string_val) {
711                 dst->string_val = NULL;
712                 return 0;
713         }
714         dst->string_val = strdup(src->string_val);
715         if (!dst->string_val) {
716                 xasprintf(errctx, "copy value for --%s", opt->name);
717                 return -E_LLS_NOMEM;
718         }
719         return 1;
720 }
721
722 int lls_check_arg_count(const struct lls_parse_result *lpr,
723                 int min_argc, int max_argc, char **errctx)
724 {
725         if (errctx)
726                 *errctx = NULL;
727         assert(min_argc <= max_argc);
728         if (lpr->num_inputs < min_argc) {
729                 xasprintf(errctx, "%s %u non-option args required, %u given",
730                         min_argc < max_argc? "at least" : "exactly",
731                         min_argc, lpr->num_inputs);
732                 return -E_LLS_BAD_ARG_COUNT;
733         }
734         if (lpr->num_inputs > max_argc) {
735                 if (max_argc == 0)
736                         xasprintf(errctx, "no non-option args allowed, "
737                                 "%u given", lpr->num_inputs);
738                 else
739                         xasprintf(errctx, "%s %u non-option args %s, %u given",
740                                 min_argc < max_argc? "at most" : "exactly",
741                                 max_argc,
742                                 min_argc < max_argc? "allowed" : "required",
743                                 lpr->num_inputs);
744                 return -E_LLS_BAD_ARG_COUNT;
745         }
746         return 1;
747 }
748
749 /*
750  * Unlike getopt(3) this implementation can not resume the scan where it left
751  * off.
752  */
753 int lls_parse(int argc, char **argv, const struct lls_command *cmd,
754                 struct lls_parse_result **lprp, char **errctx)
755 {
756         const struct lls_option *opts = cmd->options;
757         struct lls_data *d = NULL;
758         int i, ret;
759         struct lls_arg la;
760         struct lls_parse_result *lpr;
761
762         if (errctx)
763                 *errctx = NULL;
764         lpr = calloc(1, sizeof(*lpr));
765         if (!lpr) {
766                 xasprintf(errctx, "log parse result");
767                 ret = -E_LLS_NOMEM;
768                 goto out;
769         }
770         d = init_lls_data(opts, argc, argv);
771         if (!d) {
772                 xasprintf(errctx, "init_lls_data()");
773                 ret = -E_LLS_NOMEM;
774                 goto out;
775         }
776         if (cmd->num_options == 0) {
777                 la.idx = 0;
778                 lpr->opt_result = NULL;
779         } else {
780                 lpr->opt_result = calloc(cmd->num_options,
781                         sizeof(*lpr->opt_result));
782                 if (!lpr->opt_result) {
783                         xasprintf(errctx, "option result array for %s",
784                                 cmd->name);
785                         ret = -E_LLS_NOMEM;
786                         goto out;
787                 }
788                 for (;;) {
789                         ret = parse_option(d, &la, errctx);
790                         if (ret < 0)
791                                 goto out;
792                         if (ret == 0)
793                                 break;
794                         ret = lls_parse_arg(&la, opts, lpr, errctx);
795                         if (ret < 0)
796                                 goto out;
797                 }
798         }
799         lpr->num_inputs = argc - la.idx - 1;
800         if (!cmd->non_opts_name) {
801                 ret = lls_check_arg_count(lpr, 0, 0, errctx);
802                 if (ret < 0) {
803                         /* needed for lls_free_parse_result() */
804                         lpr->inputs = NULL;
805                         goto out;
806                 }
807         }
808         /* We always make a copy of the elements of argv[] */
809         lpr->inputs = malloc((lpr->num_inputs + 1) * sizeof(char *));
810         if (!lpr->inputs) {
811                 xasprintf(errctx, "inputs array for %s", cmd->name);
812                 ret = -E_LLS_NOMEM;
813                 goto out;
814         }
815         for (i = 0; i < lpr->num_inputs; i++) {
816                 char *arg = argv[i + la.idx + 1];
817                 lpr->inputs[i] = strdup(arg);
818                 if (lpr->inputs[i])
819                         continue;
820                 xasprintf(errctx, "option #%d (%s) of %s", i, arg, cmd->name);
821                 ret = -E_LLS_NOMEM;
822                 goto out;
823         }
824         lpr->inputs[lpr->num_inputs] = NULL;
825         /* initialize default values */
826         FOR_EACH_OPTION(i, opts) {
827                 const struct lls_option *opt = opts + i;
828                 struct lls_opt_result *lor = lpr->opt_result + i;
829                 bool required = opt->flags & LLS_REQUIRED;
830                 bool has_arg = opt->arg_info != LLS_NO_ARGUMENT;
831
832                 if (lor->given == 0 && required) {
833                         xasprintf(errctx, "--%s", opt->name);
834                         ret = -E_LLS_OPT_MANDATORY;
835                         goto out;
836                 }
837                 if (lor->value)
838                         continue;
839                 if (!has_arg)
840                         continue;
841                 /*
842                  * allocate space for the default value, even if there is no
843                  * default given in the .suite file
844                  */
845                 lor->value = malloc(sizeof(*lor->value));
846                 if (!lor->value) {
847                         xasprintf(errctx, "value array for --%s", opt->name);
848                         ret = -E_LLS_NOMEM;
849                         goto out;
850                 }
851                 ret = copy_val(lor->value, &opt->default_val, opt, errctx);
852                 if (ret < 0)
853                         goto out;
854         }
855         ret = 1;
856 out:
857         free(d);
858         check_errctx(errctx, ret);
859         if (ret < 0) {
860                 lls_free_parse_result(lpr, cmd);
861                 *lprp = NULL;
862         } else
863                 *lprp = lpr;
864         return ret;
865 }
866
867 #define MAX_OPTION_LEN 30
868 #define HELP_INDENT 6
869 static const char space[MAX_OPTION_LEN + 1] = "                              ";
870
871 static int short_option_help(const struct lls_option *opt, char **result)
872 {
873         int ret = 0;
874         char *opt_names = NULL;
875         bool overlong, has_short = opt->short_opt;
876         const char *typestr;
877
878         *result = NULL;
879         if (opt->flags & LLS_IGNORED)
880                 return xasprintf(result, "%s", opt->summary);
881         if (opt->arg_info == LLS_NO_ARGUMENT)
882                 typestr = "";
883         else
884                 typestr = opt->typestr? opt->typestr : "val";
885
886         ret = xasprintf(&opt_names,
887                 "%s%c%s"
888                 " --%s"
889                 "%s%s%s%s%s"
890                 ,
891                 has_short? "  -" : "   ",
892                 has_short? opt->short_opt : ' ',
893                 has_short? "," : " ",
894                 opt->name,
895                 opt->arg_info == LLS_OPTIONAL_ARGUMENT? "[" : "",
896                 opt->arg_info == LLS_NO_ARGUMENT? "" : "=<",
897                 typestr,
898                 opt->arg_info == LLS_NO_ARGUMENT? "" : ">",
899                 opt->arg_info == LLS_OPTIONAL_ARGUMENT? "]" : ""
900         );
901         if (ret < 0)
902                 return ret;
903         overlong = ret >= MAX_OPTION_LEN;
904         ret = xasprintf(result,
905                 "%s"
906                 "%s"
907                 "%s"
908                 "%s"
909                 ,
910                 opt_names,
911                 overlong? "\n" : "",
912                 overlong? space : space + ret,
913                 opt->summary? opt->summary : ""
914         );
915         free(opt_names);
916         return ret;
917 }
918
919 static int format_default_val(const struct lls_option *opt, char **result)
920 {
921         const union lls_val *val = &opt->default_val;
922
923         *result = NULL;
924         if (opt->arg_info == LLS_NO_ARGUMENT)
925                 return 0;
926         if (!(opt->flags & LLS_HAS_DEFAULT))
927                 return 0;
928         switch (opt->arg_type) {
929         case LLS_STRING:
930                 if (opt->values)
931                         return 0;
932                 return xasprintf(result, "(string, default: %s)",
933                         val->string_val? val->string_val : "[NULL]");
934         case LLS_INT32:
935                 return xasprintf(result, "(int32, default: %" PRId32 ")",
936                         val->int32_val);
937         case LLS_UINT32:
938                 return xasprintf(result, "(uint32, default: %" PRIu32 ")",
939                         val->uint32_val);
940         case LLS_INT64:
941                 return xasprintf(result, "(int64, default: %" PRId64 ")",
942                         val->int64_val);
943         case LLS_UINT64:
944                 return xasprintf(result, "(uint64, default: %" PRIu64 ")",
945                         val->uint64_val);
946         default:
947                 assert(0);
948         }
949         return 1;
950 }
951
952 static int format_values(const struct lls_option *opt, char **result)
953 {
954         int i;
955         uint32_t dflt_idx;
956         const char *val, *pfx = "values: ";
957         size_t len, line_len;
958         const int indent_len = 6, max_len = 75, pfx_len = 8;
959         char *p;
960
961         *result = NULL;
962         if (!opt->values)
963                 return 0;
964         assert(opt->arg_type == LLS_STRING);
965         dflt_idx = opt->default_val.uint32_val;
966         line_len = indent_len + pfx_len;
967         len = line_len;
968         for (i = 0; (val = opt->values[i].string_val); i++) {
969                 size_t val_len = strlen(val);
970                 /* comma and space, and [] around default val */
971                 int extra_len = 2 * (i != 0) + 2 * (i == dflt_idx);
972                 bool cr = line_len + val_len + extra_len > max_len;
973                 if (cr) {
974                         line_len = indent_len + pfx_len;
975                         len += 1 + indent_len + pfx_len; /* +1 for \n */
976                 }
977                 len += val_len + extra_len;
978                 line_len += val_len + extra_len;
979         }
980         *result = malloc(len + 1); /* +1 for terminating zero byte */
981         if (!*result)
982                 return -E_LLS_NOMEM;
983         p = *result + sprintf(*result, "%.*s%s", indent_len, space, pfx);
984         line_len = p - *result;
985         for (i = 0; (val = opt->values[i].string_val); i++) {
986                 size_t val_len = strlen(val);
987                 int extra_len = 2 * (i != 0) + 2 * (i == dflt_idx);
988                 bool cr = line_len + val_len + extra_len > max_len;
989                 p += sprintf(p,
990                         "%s"
991                         "%s"
992                         "%.*s"
993                         "%s%s%s",
994                         i == 0? "" : ", ",
995                         cr? "\n" : "",
996                         cr? pfx_len + indent_len : 0, cr? space : "",
997                         i == dflt_idx? "[" : "", val, i == dflt_idx? "]" : ""
998                 );
999                 if (cr)
1000                         line_len = indent_len + pfx_len;
1001                 line_len += val_len + extra_len;
1002         }
1003         return 1;
1004 }
1005
1006 static char *create_help_buf(const struct lls_command *cmd, bool long_help)
1007 {
1008         char *header, *option_help, *result;
1009         const struct lls_option *opt;
1010         int ret;
1011         const char *desc = (long_help && cmd->description)?
1012                 cmd->description : "";
1013         const char *closing = (long_help && cmd->closing)? cmd->closing : NULL;
1014
1015         result = NULL;
1016         header = NULL;
1017         ret = xasprintf(&header,
1018                 "%s - %s\n\n"
1019                 "Usage: %s %s\n"
1020                 "%s%s"
1021         ,
1022                 cmd->name, cmd->purpose,
1023                 cmd->name, cmd->synopsis,
1024                 desc,
1025                 cmd->options? "\n" : ""
1026         );
1027         if (ret < 0)
1028                 return NULL;
1029         if (!cmd->options)
1030                 return header;
1031         option_help = NULL;
1032         FOR_EACH_OPTION_IN_COMMAND(opt, cmd) {
1033                 char *tmp, *soh, *loh = NULL, *dflt, *values;
1034                 int indent = (opt->flags & LLS_IGNORED)? 0 : HELP_INDENT;
1035
1036                 ret = short_option_help(opt, &soh);
1037                 if (ret < 0)
1038                         goto out;
1039                 if (long_help && opt->help) {
1040                         const char *p, *q;
1041                         for (p = opt->help; (q = strchr(p, '\n')); p = q + 1) {
1042                                 tmp = NULL;
1043                                 ret = xasprintf(&tmp, "%s%.*s%.*s",
1044                                         loh? loh : "\n", indent, space,
1045                                         (int)(q - p + 1), p);
1046                                 free(loh);
1047                                 if (ret < 0) {
1048                                         free(soh);
1049                                         goto out;
1050                                 }
1051                                 loh = tmp;
1052                         }
1053                 }
1054                 ret = format_default_val(opt, &dflt);
1055                 if (ret < 0) {
1056                         free(soh);
1057                         free(loh);
1058                         goto out;
1059                 }
1060                 if (long_help) {
1061                         ret = format_values(opt, &values);
1062                         if (ret < 0) {
1063                                 free(dflt);
1064                                 free(soh);
1065                                 free(loh);
1066                                 goto out;
1067                         }
1068                 } else
1069                         values = NULL;
1070                 tmp = NULL;
1071                 ret = xasprintf(&tmp,
1072                         "%s"
1073                         "%s"
1074                         "%s%s%s"
1075                         "%s%s"
1076                         "%s\n",
1077                         option_help? option_help : "",
1078                         soh ? soh : "",
1079                         dflt? "\n" : "", dflt? space : "", dflt? dflt : "",
1080                         values? "\n" : "", values? values : "",
1081                         loh? loh : ""
1082                 );
1083                 free(values);
1084                 free(dflt);
1085                 free(soh);
1086                 free(loh);
1087                 if (ret < 0)
1088                         goto out;
1089                 free(option_help);
1090                 option_help = tmp;
1091         }
1092         ret = xasprintf(&result, "%s%s%s%s", header, option_help,
1093                 closing? "\n" : "", closing? closing : "");
1094 out:
1095         free(header);
1096         free(option_help);
1097         return ret < 0? NULL : result;
1098 }
1099
1100 char *lls_long_help(const struct lls_command *cmd)
1101 {
1102         return create_help_buf(cmd, true /* include help */);
1103 }
1104
1105 char *lls_short_help(const struct lls_command *cmd)
1106 {
1107         return create_help_buf(cmd, false /* only options */);
1108 }
1109
1110 static int partial_match(const char *arg, const char *name)
1111 {
1112         size_t arglen = strlen(arg);
1113
1114         if (strncmp(arg, name, arglen) != 0)
1115                 return 1; /* no match */
1116         if (name[arglen] == '\0')
1117                 return 0; /* exact match */
1118         return -1; /* partial match */
1119 }
1120
1121 int lls_lookup_subcmd(const char *string, const struct lls_suite *suite,
1122                 char **errctx)
1123 {
1124         int i, ret;
1125
1126         if (errctx)
1127                 *errctx = NULL;
1128         if (!string) {
1129                 xasprintf(errctx, "nothing to look up");
1130                 return -E_LLS_BAD_SUBCMD;
1131         }
1132         ret = 0; /* no match so far */
1133         for (i = 1; i <= suite->num_subcommands; i++) {
1134                 switch (partial_match(string, suite->commands[i].name)) {
1135                 case 1: /* no match */
1136                         continue;
1137                 case 0: /* exact match */
1138                         return i;
1139                 case -1: /* partial match */
1140                         if (ret > 0) {
1141                                 ret = -E_LLS_AMBIG_SUBCMD;
1142                                 goto fail;
1143                         }
1144                         ret = i;
1145                 }
1146         }
1147         if (ret > 0) /* unique partial match */
1148                 return ret;
1149         ret = -E_LLS_BAD_SUBCMD;
1150 fail:
1151         xasprintf(errctx, "%s", string);
1152         return ret;
1153 }
1154
1155 static size_t get_opt_result_pointer(const struct lls_option *opt, int val_num,
1156                 struct lls_opt_result *lor, void **result)
1157 {
1158         union lls_val *val = lor->value + val_num;
1159
1160         switch (opt->arg_type) {
1161         case LLS_INT32:
1162                 *result = &val->int32_val;
1163                 return 4;
1164         case LLS_UINT32:
1165                 *result = &val->uint32_val;
1166                 return 4;
1167         case LLS_INT64:
1168                 *result = &val->int64_val;
1169                 return 8;
1170         case LLS_UINT64:
1171                 *result = &val->uint64_val;
1172                 return 8;
1173         default:
1174                 assert(0);
1175         }
1176 }
1177
1178 /* never fails, returns number of bytes needed/written */
1179 static size_t serialize_parse_result(const struct lls_parse_result *lpr,
1180         const struct lls_command *cmd, char *result)
1181 {
1182         int i, j;
1183         size_t nbytes;
1184
1185         /* num_inputs */
1186         if (result)
1187                 memcpy(result, &lpr->num_inputs, 4);
1188         nbytes = 4;
1189
1190         /* inputs */
1191         for (i = 0; i < lpr->num_inputs; i++) {
1192                 if (result)
1193                         strcpy(result + nbytes, lpr->inputs[i]);
1194                 nbytes += strlen(lpr->inputs[i]) + 1;
1195         }
1196         /* options */
1197         FOR_EACH_OPTION(i, cmd->options) {
1198                 const struct lls_option *opt = cmd->options + i;
1199                 struct lls_opt_result *lor = lpr->opt_result + i;
1200                 unsigned num_vals;
1201
1202                 if (result)
1203                         memcpy(result + nbytes, &lor->given, 4);
1204                 nbytes += 4;
1205                 if (opt->arg_info == LLS_NO_ARGUMENT)
1206                         continue;
1207                 num_vals = num_vals_in_parse_result(cmd, i, lpr);
1208                 if (opt->arg_type == LLS_STRING && !opt->values) {
1209                         for (j = 0; j < num_vals; j++) {
1210                                 if (result)
1211                                         strcpy(result + nbytes,
1212                                                 lor->value[j].string_val);
1213                                 nbytes += strlen(lor->value[j].string_val) + 1;
1214                         }
1215                 } else {
1216                         for (j = 0; j < num_vals; j++) {
1217                                 size_t bytes;
1218                                 void *p;
1219                                 bytes = get_opt_result_pointer(opt, j, lor, &p);
1220                                 if (result)
1221                                         memcpy(result + nbytes, p, bytes);
1222                                 nbytes += bytes;
1223                         }
1224                 }
1225         }
1226         return nbytes;
1227 }
1228
1229 int lls_serialize_parse_result(const struct lls_parse_result *lpr,
1230         const struct lls_command *cmd, char **result, size_t *nbytes)
1231 {
1232         size_t sz;
1233         int ret;
1234
1235         if (!result || !*result) { /* need to compute needed space */
1236                 sz = serialize_parse_result(lpr, cmd, NULL);
1237                 if (!result) { /* just report needed space */
1238                         ret = 0;
1239                         goto out;
1240                 }
1241                 *result = malloc(sz);
1242                 if (!*result) {
1243                         sz = 0;
1244                         ret = -E_LLS_NOMEM;
1245                         goto out;
1246                 }
1247         }
1248         /* serialize it */
1249         sz = serialize_parse_result(lpr, cmd, *result);
1250         ret = 1;
1251 out:
1252         if (nbytes)
1253                 *nbytes = sz;
1254         return ret;
1255 }
1256
1257 int lls_deserialize_parse_result(const char *buf, const struct lls_command *cmd,
1258                 struct lls_parse_result **lprp)
1259 {
1260         int i, j;
1261         const char *p = buf;
1262         struct lls_parse_result *lpr;
1263
1264         *lprp = NULL;
1265         lpr = malloc(sizeof(*lpr));
1266         if (!lpr)
1267                 return -E_LLS_NOMEM;
1268         memcpy(&lpr->num_inputs, p, 4);
1269         p += 4;
1270         if (lpr->num_inputs > 0) {
1271                 lpr->inputs = malloc(lpr->num_inputs * sizeof(char *));
1272                 if (!lpr->inputs)
1273                         goto free_lpr;
1274         } else
1275                 lpr->inputs = NULL;
1276         for (i = 0; i < lpr->num_inputs; i++) {
1277                 lpr->inputs[i] = strdup(p);
1278                 if (!lpr->inputs[i])
1279                         goto free_inputs;
1280                 p += strlen(p) + 1;
1281         }
1282         lpr->opt_result = malloc(cmd->num_options * sizeof(*lpr->opt_result));
1283         if (!lpr->opt_result)
1284                 goto free_inputs;
1285         FOR_EACH_OPTION(i, cmd->options) {
1286                 const struct lls_option *opt = cmd->options + i;
1287                 struct lls_opt_result *lor = lpr->opt_result + i;
1288                 uint32_t num_vals;
1289
1290                 memcpy(&lor->given, p, 4);
1291                 p += 4;
1292                 if (opt->arg_info == LLS_NO_ARGUMENT)
1293                         continue;
1294                 num_vals = num_vals_in_parse_result(cmd, i, lpr);
1295                 lor->value = malloc(num_vals * sizeof(*lor->value));
1296                 if (!lor->value)
1297                         goto free_options;
1298                 if (opt->arg_type == LLS_STRING && !opt->values) {
1299                         for (j = 0; j < num_vals; j++) {
1300                                 lor->value[j].string_val = strdup(p);
1301                                 if (!lor->value[j].string_val) {
1302                                         for (; j >= 0; j--)
1303                                                 free(lor->value[j].string_val);
1304                                         free(lor->value);
1305                                         goto free_options;
1306                                 }
1307                                 p += strlen(lor->value[j].string_val) + 1;
1308                         }
1309                 } else {
1310                         for (j = 0; j < num_vals; j++) {
1311                                 size_t bytes;
1312                                 void *q;
1313                                 bytes = get_opt_result_pointer(opt, j, lor, &q);
1314                                 memcpy(q, p, bytes);
1315                                 p += bytes;
1316                         }
1317                 }
1318         }
1319         *lprp = lpr;
1320         return 1;
1321 free_options:
1322         for (i--; i >= 0; i--) {
1323                 const struct lls_option *opt = cmd->options + i;
1324                 struct lls_opt_result *lor = lpr->opt_result + i;
1325                 unsigned num_vals = (opt->flags & LLS_MULTIPLE)? lor->given : 1;
1326                 for (j = 0; j < num_vals; j++)
1327                         if (opt->arg_type == LLS_STRING && !opt->values)
1328                                 free(lor->value[j].string_val);
1329                 free(lor->value);
1330         }
1331         free(lpr->opt_result);
1332 free_inputs:
1333         for (; i >= 0; i--)
1334                 free(lpr->inputs[i]);
1335         free(lpr->inputs);
1336 free_lpr:
1337         free(lpr);
1338         return -E_LLS_NOMEM;
1339 }
1340
1341 static int merge_option(int opt_num, const struct lls_parse_result *primary,
1342                 const struct lls_parse_result *secondary,
1343                 const struct lls_command *cmd, struct lls_parse_result *result,
1344                 char **errctx)
1345 {
1346         int l, m, ret;
1347         const struct lls_option *opt = cmd->options + opt_num;
1348         struct lls_opt_result *lor1, *lor2, *lor;
1349
1350         lor1 = primary->opt_result + opt_num;
1351         lor2 = secondary->opt_result + opt_num;
1352         lor = result->opt_result + opt_num;
1353         lor->given = lor1->given + lor2->given;
1354         if (opt->arg_info == LLS_NO_ARGUMENT)
1355                 return 0;
1356         if (lor->given > 0 && (opt->flags & LLS_MULTIPLE)) {
1357                 lor->value = malloc(lor->given * sizeof(*lor->value));
1358                 if (!lor->value) {
1359                         xasprintf(errctx, "value array for option %s", opt->name);
1360                         goto fail;
1361                 }
1362                 for (l = 0; l < lor1->given; l++) {
1363                         ret = copy_val(lor->value + l, lor1->value + l,
1364                                 opt, errctx);
1365                         if (ret < 0)
1366                                 goto free_primary_options;
1367                 }
1368                 for (m = 0; m < lor2->given; m++) {
1369                         ret = copy_val(lor->value + l + m, lor2->value + m,
1370                                 opt, errctx);
1371                         if (ret < 0)
1372                                 goto free_secondary_options;
1373                 }
1374                 return 1;
1375         }
1376         lor->value = malloc(sizeof(*lor->value)); /* one value only */
1377         if (!lor->value) {
1378                 xasprintf(errctx, "(single) value for option %s", opt->name);
1379                 goto fail;
1380         }
1381         if (lor1->given) {
1382                 ret = copy_val(lor->value, lor1->value, opt, errctx);
1383                 if (ret < 0)
1384                         goto free_value;
1385         } else if (lor2->given) {
1386                 ret = copy_val(lor->value, lor2->value, opt, errctx);
1387                 if (ret < 0)
1388                         goto free_value;
1389         } else {
1390                 ret = copy_val(lor->value, &opt->default_val, opt, errctx);
1391                 if (ret < 0)
1392                         goto free_value;
1393         }
1394         return 1;
1395 free_secondary_options:
1396         if (opt->arg_type == LLS_STRING && !opt->values)
1397                 for (m--; m >= 0; m--)
1398                         free(lor->value[l + m].string_val);
1399 free_primary_options:
1400         if (opt->arg_type == LLS_STRING && !opt->values)
1401                 for (l--; l >= 0; l--)
1402                         free(lor->value[l].string_val);
1403 free_value:
1404         free(lor->value);
1405 fail:
1406         return -E_LLS_NOMEM;
1407 }
1408
1409 int lls_merge(const struct lls_parse_result *primary,
1410                 const struct lls_parse_result *secondary,
1411                 const struct lls_command *cmd, struct lls_parse_result **lprp,
1412                 char **errctx)
1413 {
1414         int i, j, k, ret;
1415         unsigned num = primary->num_inputs + secondary->num_inputs;
1416         struct lls_parse_result *result;
1417
1418         if (errctx)
1419                 *errctx = NULL;
1420         result = malloc(sizeof(*result));
1421         if (!result) {
1422                 ret = -E_LLS_NOMEM;
1423                 xasprintf(errctx, "parse result");
1424                 goto fail;
1425         }
1426         result->inputs = malloc((num + 1) * sizeof(char *));
1427         if (!result->inputs) {
1428                 ret = -E_LLS_NOMEM;
1429                 xasprintf(errctx, "inputs array of size %u", num);
1430                 goto free_parse_result;
1431         }
1432         for (i = 0; i < primary->num_inputs; i++) {
1433                 result->inputs[i] = strdup(primary->inputs[i]);
1434                 if (!result->inputs[i]) {
1435                         ret = -E_LLS_NOMEM;
1436                         xasprintf(errctx, "primary input #%d", i);
1437                         goto free_primary_inputs;
1438                 }
1439         }
1440         for (j = 0; j < secondary->num_inputs; j++) {
1441                 result->inputs[i + j] = strdup(secondary->inputs[j]);
1442                 if (!result->inputs[i + j]) {
1443                         ret = -E_LLS_NOMEM;
1444                         xasprintf(errctx, "secondary input #%d", i);
1445                         goto free_secondary_inputs;
1446                 }
1447         }
1448         result->inputs[i + j] = NULL;
1449         result->opt_result = malloc(cmd->num_options
1450                 * sizeof(*result->opt_result));
1451         if (!result->opt_result)
1452                 goto free_secondary_inputs;
1453         FOR_EACH_OPTION(k, cmd->options) {
1454                 ret = merge_option(k, primary, secondary, cmd, result, errctx);
1455                 if (ret < 0)
1456                         goto free_opt_results;
1457         }
1458         result->num_inputs = num;
1459         *lprp = result;
1460         ret = 1;
1461         goto out;
1462 free_opt_results:
1463         for (k--; k >= 0; k--)
1464                 free_opt_result(k, result, cmd);
1465 free_secondary_inputs:
1466         for (j--; j >= 0; j--)
1467                 free(result->inputs[i + j]);
1468 free_primary_inputs:
1469         for (i--; i >= 0; i--)
1470                 free(result->inputs[i]);
1471         free(result->inputs);
1472 free_parse_result:
1473         free(result);
1474 fail:
1475         assert(ret < 0);
1476         *lprp = NULL;
1477 out:
1478         check_errctx(errctx, ret);
1479         return ret;
1480 }
1481
1482 static bool is_default_val(const union lls_val *val,
1483                 const struct lls_option *opt)
1484 {
1485         bool has_default = opt->flags & LLS_HAS_DEFAULT;
1486         bool has_arg = opt->arg_info != LLS_NO_ARGUMENT;
1487         const union lls_val *dflt;
1488
1489         if (!has_arg)
1490                 return false;
1491         if (!has_default)
1492                 return false;
1493         dflt = &opt->default_val;
1494         switch (opt->arg_type) {
1495         case LLS_INT32:
1496                 return val->int32_val == dflt->int32_val;
1497         case LLS_UINT32:
1498                 return val->uint32_val == dflt->uint32_val;
1499         case LLS_INT64:
1500                 return val->int64_val == dflt->int64_val;
1501         case LLS_UINT64:
1502                 return val->uint64_val == dflt->uint64_val;
1503         case LLS_STRING:
1504                 {
1505                 const char *s1, *s2;
1506
1507                 if (opt->values)
1508                         return val->uint32_val == dflt->uint32_val;
1509                 s1 = val->string_val;
1510                 s2 = dflt->string_val;
1511                 if (!s1 && !s2)
1512                         return true;
1513                 if (!s1 || !s2)
1514                         return false;
1515                 return !strcmp(s1, s2);
1516                 }
1517         default:
1518                 assert(0);
1519         }
1520 }
1521
1522 static char *append_opt_val(const union lls_val *val,
1523                 const struct lls_option *opt, char *result)
1524 {
1525         char *line = NULL, *tmp = NULL;
1526
1527         switch (opt->arg_type) {
1528         case LLS_INT32:
1529                 xasprintf(&line, "%" PRId32, val->int32_val);
1530                 break;
1531         case LLS_UINT32:
1532                 xasprintf(&line, "%" PRIu32, val->uint32_val);
1533                 break;
1534         case LLS_INT64:
1535                 xasprintf(&line, "%" PRId64, val->int64_val);
1536                 break;
1537         case LLS_UINT64:
1538                 xasprintf(&line, "%" PRIu64, val->uint64_val);
1539                 break;
1540         case LLS_STRING:
1541                 {
1542                 const char *s, *p;
1543                 char *q;
1544
1545                 if (opt->values)
1546                         s = lls_enum_string_val(val->uint32_val, opt);
1547                 else {
1548                         s = val->string_val;
1549                         if (!s)
1550                                 return result;
1551                 }
1552                 line = malloc(2 * strlen(s) + 3);
1553                 if (!line) {
1554                         free(result);
1555                         return NULL;
1556                 }
1557                 line[0] = '"';
1558                 for (p = s, q = line + 1; *p; p++, q++) {
1559                         if (*p == '\\' || *p == '\n' || *p == '\t' || *p == '"') {
1560                                 *q = '\\';
1561                                 q++;
1562                         }
1563                         *q = *p;
1564                 }
1565                 q[0] = '"';
1566                 q[1] = '\0';
1567                 break;
1568                 }
1569         default:
1570                 assert(0);
1571         }
1572         xasprintf(&tmp, "%s%s=%s\n", result? result : "", opt->name, line);
1573         free(line);
1574         free(result);
1575         return tmp;
1576 }
1577
1578 char *lls_dump_parse_result(const struct lls_parse_result *lpr,
1579                 const struct lls_command *cmd, bool non_default_only)
1580 {
1581         int i;
1582         char *result = NULL;
1583
1584         FOR_EACH_OPTION(i, cmd->options) {
1585                 const struct lls_option *opt = cmd->options + i;
1586                 struct lls_opt_result *lor = lpr->opt_result + i;
1587                 bool given = lor->given;
1588                 int j, n;
1589
1590                 if (!given && non_default_only)
1591                         continue;
1592                 if (opt->arg_info == LLS_NO_ARGUMENT) {
1593                         char *tmp = NULL;
1594                         if (!given)
1595                                 continue;
1596                         xasprintf(&tmp, "%s%s\n", result? result : "",
1597                                 opt->name);
1598                         free(result);
1599                         result = tmp;
1600                         continue;
1601                 }
1602                 n = num_vals_in_parse_result(cmd, i, lpr);
1603                 for (j = 0; j < n; j++) {
1604                         union lls_val *val = lor->value + j;
1605                         if (non_default_only && is_default_val(val, opt))
1606                                 continue;
1607                         result = append_opt_val(val, opt, result);
1608                 }
1609         }
1610         if (!result) { /* empty dump */
1611                 result = malloc(1);
1612                 if (result)
1613                         result[0] = '\0';
1614         }
1615         return result;
1616 }