b74d74fe98792ac314094be4bf927b1e11b51fb3
[sigrok-cli.git] / parsers.c
1 /*
2  * This file is part of the sigrok-cli project.
3  *
4  * Copyright (C) 2011 Bert Vermeulen <bert@biot.com>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdint.h>
24 #include <string.h>
25 #include <glib.h>
26 #include "sigrok-cli.h"
27
28 struct sr_channel *find_channel(GSList *channellist, const char *channelname)
29 {
30         struct sr_channel *ch;
31         GSList *l;
32
33         ch = NULL;
34         for (l = channellist; l; l = l->next) {
35                 ch = l->data;
36                 if (!strcmp(ch->name, channelname))
37                         break;
38         }
39         ch = l ? l->data : NULL;
40
41         return ch;
42 }
43
44 GSList *parse_channelstring(struct sr_dev_inst *sdi, const char *channelstring)
45 {
46         struct sr_channel *ch;
47         GSList *channellist, *channels;
48         int ret, n, b, e, i;
49         char **tokens, **range, **names, *eptr, str[8];
50
51         channels = sr_dev_inst_channels_get(sdi);
52
53         if (!channelstring || !channelstring[0])
54                 /* Use all channels by default. */
55                 return g_slist_copy(channels);
56
57         ret = SR_OK;
58         range = NULL;
59         names = NULL;
60         channellist = NULL;
61         tokens = g_strsplit(channelstring, ",", 0);
62         for (i = 0; tokens[i]; i++) {
63                 if (tokens[i][0] == '\0') {
64                         g_critical("Invalid empty channel.");
65                         ret = SR_ERR;
66                         break;
67                 }
68                 if (strchr(tokens[i], '-')) {
69                         /*
70                          * A range of channels in the form a-b. This will only work
71                          * if the channels are named as numbers -- so every channel
72                          * in the range must exist as a channel name string in the
73                          * device.
74                          */
75                         range = g_strsplit(tokens[i], "-", 2);
76                         if (!range[0] || !range[1] || range[2]) {
77                                 /* Need exactly two arguments. */
78                                 g_critical("Invalid channel syntax '%s'.", tokens[i]);
79                                 ret = SR_ERR;
80                                 goto range_fail;
81                         }
82
83                         b = strtol(range[0], &eptr, 10);
84                         if (eptr == range[0] || *eptr != '\0') {
85                                 g_critical("Invalid channel '%s'.", range[0]);
86                                 ret = SR_ERR;
87                                 goto range_fail;
88                         }
89                         e = strtol(range[1], NULL, 10);
90                         if (eptr == range[1] || *eptr != '\0') {
91                                 g_critical("Invalid channel '%s'.", range[1]);
92                                 ret = SR_ERR;
93                                 goto range_fail;
94                         }
95                         if (b < 0 || b >= e) {
96                                 g_critical("Invalid channel range '%s'.", tokens[i]);
97                                 ret = SR_ERR;
98                                 goto range_fail;
99                         }
100
101                         while (b <= e) {
102                                 n = snprintf(str, 8, "%d", b);
103                                 if (n < 0 || n > 8) {
104                                         g_critical("Invalid channel '%d'.", b);
105                                         ret = SR_ERR;
106                                         break;
107                                 }
108                                 ch = find_channel(channels, str);
109                                 if (!ch) {
110                                         g_critical("unknown channel '%d'.", b);
111                                         ret = SR_ERR;
112                                         break;
113                                 }
114                                 channellist = g_slist_append(channellist, ch);
115                                 b++;
116                         }
117 range_fail:
118                         if (range)
119                                 g_strfreev(range);
120
121                         if (ret != SR_OK)
122                                 break;
123                 } else {
124                         names = g_strsplit(tokens[i], "=", 2);
125                         if (!names[0] || (names[1] && names[2])) {
126                                 /* Need one or two arguments. */
127                                 g_critical("Invalid channel '%s'.", tokens[i]);
128                                 g_strfreev(names);
129                                 ret = SR_ERR;
130                                 break;
131                         }
132
133                         ch = find_channel(channels, names[0]);
134                         if (!ch) {
135                                 g_critical("unknown channel '%s'.", names[0]);
136                                 g_strfreev(names);
137                                 ret = SR_ERR;
138                                 break;
139                         }
140                         if (names[1]) {
141                                 /* Rename channel. */
142                                 sr_dev_channel_name_set(ch, names[1]);
143                         }
144                         channellist = g_slist_append(channellist, ch);
145
146                         g_strfreev(names);
147                 }
148         }
149
150         if (ret != SR_OK) {
151                 g_slist_free(channellist);
152                 channellist = NULL;
153         }
154
155         g_strfreev(tokens);
156
157         return channellist;
158 }
159
160 int parse_trigger_match(char c)
161 {
162         int match;
163
164         if (c == '0')
165                 match = SR_TRIGGER_ZERO;
166         else if (c == '1')
167                 match = SR_TRIGGER_ONE;
168         else if (c == 'r')
169                 match = SR_TRIGGER_RISING;
170         else if (c == 'f')
171                 match = SR_TRIGGER_FALLING;
172         else if (c == 'e')
173                 match = SR_TRIGGER_EDGE;
174         else if (c == 'o')
175                 match = SR_TRIGGER_OVER;
176         else if (c == 'u')
177                 match = SR_TRIGGER_UNDER;
178         else
179                 match = 0;
180
181         return match;
182 }
183
184 int parse_triggerstring(const struct sr_dev_inst *sdi, const char *s,
185                 struct sr_trigger **trigger)
186 {
187         struct sr_channel *ch;
188         struct sr_trigger_stage *stage;
189         GVariant *gvar;
190         GSList *l, *channels;
191         gsize num_matches;
192         gboolean found_match, error;
193         const int32_t *matches;
194         int32_t match;
195         unsigned int j;
196         int t, i;
197         char **tokens, *sep;
198         struct sr_dev_driver *driver;
199
200         driver = sr_dev_inst_driver_get(sdi);
201         channels = sr_dev_inst_channels_get(sdi);
202
203         if (maybe_config_list(driver, sdi, NULL, SR_CONF_TRIGGER_MATCH,
204                         &gvar) != SR_OK) {
205                 g_critical("Device doesn't support any triggers.");
206                 return FALSE;
207         }
208         matches = g_variant_get_fixed_array(gvar, &num_matches, sizeof(int32_t));
209
210         *trigger = sr_trigger_new(NULL);
211         error = FALSE;
212         tokens = g_strsplit(s, ",", -1);
213         for (i = 0; tokens[i]; i++) {
214                 if (!(sep = strchr(tokens[i], '='))) {
215                         g_critical("Invalid trigger '%s'.", tokens[i]);
216                         error = TRUE;
217                         break;
218                 }
219                 *sep++ = 0;
220                 ch = NULL;
221                 for (l = channels; l; l = l->next) {
222                         ch = l->data;
223                         if (ch->enabled && !strcmp(ch->name, tokens[i]))
224                                 break;
225                         ch = NULL;
226                 }
227                 if (!ch) {
228                         g_critical("Invalid channel '%s'.", tokens[i]);
229                         error = TRUE;
230                         break;
231                 }
232                 for (t = 0; sep[t]; t++) {
233                         if (!(match = parse_trigger_match(sep[t]))) {
234                                 g_critical("Invalid trigger match '%c'.", sep[t]);
235                                 error = TRUE;
236                                 break;
237                         }
238                         found_match = FALSE;
239                         for (j = 0; j < num_matches; j++) {
240                                 if (matches[j] == match) {
241                                         found_match = TRUE;
242                                         break;
243                                 }
244                         }
245                         if (!found_match) {
246                                 g_critical("Trigger match '%c' not supported by device.", sep[t]);
247                                 error = TRUE;
248                                 break;
249                         }
250                         /* Make sure this ends up in the right stage, creating
251                          * them as needed. */
252                         while (!(stage = g_slist_nth_data((*trigger)->stages, t)))
253                                 sr_trigger_stage_add(*trigger);
254                         if (sr_trigger_match_add(stage, ch, match, 0) != SR_OK) {
255                                 error = TRUE;
256                                 break;
257                         }
258                 }
259         }
260         g_strfreev(tokens);
261         g_variant_unref(gvar);
262
263         if (error)
264                 sr_trigger_free(*trigger);
265
266         return !error;
267 }
268
269 /**
270  * Split an input text into a key and value respectively ('=' separator).
271  *
272  * @param[in] text Writeable copy of the input text, gets modified.
273  * @param[out] key Position of the keyword.
274  * @param[out] val Position of the value.
275  *
276  * TODO In theory the returned key/value locations could be const pointers.
277  * Which even would be preferrable. Unfortunately most call sites deal with
278  * glib hashes, and their insert API seriously lacks the const attribute.
279  * So we drop it here as well to avoid clutter at callers'.
280  */
281 static void split_key_value(char *text, char **key, char **val)
282 {
283         char *k, *v;
284         char *pos;
285
286         if (key)
287                 *key = NULL;
288         if (val)
289                 *val = NULL;
290         if (!text || !*text)
291                 return;
292
293         k = text;
294         v = NULL;
295         pos = strchr(k, '=');
296         if (pos) {
297                 *pos = '\0';
298                 v = ++pos;
299         }
300         if (key)
301                 *key = k;
302         if (val)
303                 *val = v;
304 }
305
306 /**
307  * Create hash table from colon separated key-value pairs input text.
308  *
309  * Accepts input text as it was specified by users. Splits the colon
310  * separated key-value pairs and creates a hash table from these items.
311  * Optionally supports special forms which are useful for different CLI
312  * features.
313  *
314  * Typical form: <key>=<val>[:<key>=<val>]*
315  * Generic list of key-value pairs, all items being equal. Mere set.
316  *
317  * ID form: <id>[:<key>=<val>]*
318  * First item is not a key-value pair, instead it's an identifier. Used
319  * to specify a protocol decoder, or a device driver, or an input/output
320  * file format, optionally followed by more parameters' values. The ID
321  * part of the input spec is not optional.
322  *
323  * Optional ID: [<sel>=<id>][:<key>=<val>]*
324  * All items are key-value pairs. The first item _may_ be an identifier,
325  * if its key matches a caller specified key name. Otherwise the input
326  * text is the above typical form, a mere list of key-value pairs while
327  * none of them is special.
328  *
329  * @param[in] arg Input text.
330  * @param[in] sep_first Boolean, whether ID form is required.
331  * @param[in] key_first Keyword name if optional ID is applicable.
332  *
333  * @returns A hash table which contains the key/value pairs, or #NULL
334  *   when the input is invalid.
335  */
336 GHashTable *parse_generic_arg(const char *arg,
337         gboolean sep_first, const char *key_first)
338 {
339         GHashTable *hash;
340         char **elements;
341         int i;
342         char *k, *v;
343
344         if (!arg || !arg[0])
345                 return NULL;
346         if (key_first && !key_first[0])
347                 key_first = NULL;
348
349         hash = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
350         elements = g_strsplit(arg, ":", 0);
351         i = 0;
352         if (sep_first) {
353                 k = g_strdup("sigrok_key");
354                 v = g_strdup(elements[i++]);
355                 g_hash_table_insert(hash, k, v);
356         } else if (key_first) {
357                 split_key_value(elements[i], &k, &v);
358                 if (g_ascii_strcasecmp(k, key_first) == 0) {
359                         k = "sigrok_key";
360                 }
361                 k = g_strdup(k);
362                 v = g_strdup(v);
363                 g_hash_table_insert(hash, k, v);
364                 i++;
365         }
366         for (; elements[i]; i++) {
367                 split_key_value(elements[i], &k, &v);
368                 k = g_strdup(k);
369                 v = v ? g_strdup(v) : NULL;
370                 g_hash_table_insert(hash, k, v);
371         }
372         g_strfreev(elements);
373
374         return hash;
375 }
376
377 GSList *check_unknown_keys(const struct sr_option **avail, GHashTable *used)
378 {
379         GSList *unknown;
380         GHashTableIter iter;
381         void *key;
382         const char *used_id;
383         size_t avail_idx;
384         const char *avail_id, *found_id;
385
386         /* Collect a list of used but not available keywords. */
387         unknown = NULL;
388         g_hash_table_iter_init(&iter, used);
389         while (g_hash_table_iter_next(&iter, &key, NULL)) {
390                 used_id = key;
391                 found_id = NULL;
392                 for (avail_idx = 0; avail[avail_idx] && avail[avail_idx]->id; avail_idx++) {
393                         avail_id = avail[avail_idx]->id;
394                         if (strcmp(avail_id, used_id) == 0) {
395                                 found_id = avail_id;
396                                 break;
397                         }
398                 }
399                 if (!found_id)
400                         unknown = g_slist_append(unknown, g_strdup(used_id));
401         }
402
403         /* Return the list of unknown keywords, or NULL if empty. */
404         return unknown;
405 }
406
407 gboolean warn_unknown_keys(const struct sr_option **avail, GHashTable *used,
408         const char *caption)
409 {
410         GSList *unknown, *l;
411         gboolean had_unknown;
412         const char *s;
413
414         if (!caption || !*caption)
415                 caption = "Unknown keyword";
416
417         unknown = check_unknown_keys(avail, used);
418         had_unknown = unknown != NULL;
419         for (l = unknown; l; l = l->next) {
420                 s = l->data;
421                 g_warning("%s: %s.", caption, s);
422         }
423         g_slist_free_full(unknown, g_free);
424
425         return had_unknown;
426 }
427
428 GHashTable *generic_arg_to_opt(const struct sr_option **opts, GHashTable *genargs)
429 {
430         GHashTable *hash;
431         GVariant *gvar;
432         int i;
433         char *s;
434         gboolean b;
435
436         hash = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
437                         (GDestroyNotify)g_variant_unref);
438         for (i = 0; opts[i]; i++) {
439                 if (!(s = g_hash_table_lookup(genargs, opts[i]->id)))
440                         continue;
441                 if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_UINT32)) {
442                         gvar = g_variant_new_uint32(strtoul(s, NULL, 10));
443                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
444                                         g_variant_ref_sink(gvar));
445                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_INT32)) {
446                         gvar = g_variant_new_int32(strtol(s, NULL, 10));
447                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
448                                         g_variant_ref_sink(gvar));
449                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_UINT64)) {
450                         gvar = g_variant_new_uint64(strtoull(s, NULL, 10));
451                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
452                                         g_variant_ref_sink(gvar));
453                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_DOUBLE)) {
454                         gvar = g_variant_new_double(strtod(s, NULL));
455                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
456                                         g_variant_ref_sink(gvar));
457                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_STRING)) {
458                         gvar = g_variant_new_string(s);
459                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
460                                         g_variant_ref_sink(gvar));
461                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_BOOLEAN)) {
462                         b = TRUE;
463                         if (0 == strcmp(s, "false") || 0 == strcmp(s, "no")) {
464                                 b = FALSE;
465                         } else if (!(0 == strcmp(s, "true") || 0 == strcmp(s, "yes"))) {
466                                 g_critical("Unable to convert '%s' to boolean!", s);
467                         }
468
469                         gvar = g_variant_new_boolean(b);
470                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
471                                         g_variant_ref_sink(gvar));
472                 } else {
473                         g_critical("Don't know GVariant type for option '%s'!", opts[i]->id);
474                  }
475         }
476
477         return hash;
478 }
479
480 static char *strcanon(const char *str)
481 {
482         int p0, p1;
483         char *s;
484
485         /* Returns newly allocated string. */
486         s = g_ascii_strdown(str, -1);
487         for (p0 = p1 = 0; str[p0]; p0++) {
488                 if ((s[p0] >= 'a' && s[p0] <= 'z')
489                                 || (s[p0] >= '0' && s[p0] <= '9'))
490                         s[p1++] = s[p0];
491         }
492         s[p1] = '\0';
493
494         return s;
495 }
496
497 int canon_cmp(const char *str1, const char *str2)
498 {
499         int ret;
500         char *s1, *s2;
501
502         s1 = strcanon(str1);
503         s2 = strcanon(str2);
504         ret = g_ascii_strcasecmp(s1, s2);
505         g_free(s2);
506         g_free(s1);
507
508         return ret;
509 }
510
511 /* Convert driver options hash to GSList of struct sr_config. */
512 static GSList *hash_to_hwopt(GHashTable *hash)
513 {
514         struct sr_config *src;
515         GList *gl, *keys;
516         GSList *opts;
517         char *key;
518
519         keys = g_hash_table_get_keys(hash);
520         opts = NULL;
521         for (gl = keys; gl; gl = gl->next) {
522                 key = gl->data;
523                 src = g_malloc(sizeof(struct sr_config));
524                 if (opt_to_gvar(key, g_hash_table_lookup(hash, key), src) != 0)
525                         return NULL;
526                 opts = g_slist_append(opts, src);
527         }
528         g_list_free(keys);
529
530         return opts;
531 }
532
533 int parse_driver(char *arg, struct sr_dev_driver **driver, GSList **drvopts)
534 {
535         struct sr_dev_driver **drivers;
536         GHashTable *drvargs;
537         int i;
538         char *drvname;
539
540         if (!arg)
541                 return FALSE;
542
543         drvargs = parse_generic_arg(arg, TRUE, NULL);
544
545         drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
546         g_hash_table_remove(drvargs, "sigrok_key");
547         *driver = NULL;
548         drivers = sr_driver_list(sr_ctx);
549         for (i = 0; drivers[i]; i++) {
550                 if (strcmp(drivers[i]->name, drvname))
551                         continue;
552                 *driver = drivers[i];
553         }
554         if (!*driver) {
555                 g_critical("Driver %s not found.", drvname);
556                 g_hash_table_destroy(drvargs);
557                 g_free(drvname);
558                 return FALSE;
559         }
560         g_free(drvname);
561         if (sr_driver_init(sr_ctx, *driver) != SR_OK) {
562                 g_critical("Failed to initialize driver.");
563                 g_hash_table_destroy(drvargs);
564                 return FALSE;
565         }
566
567         if (drvopts) {
568                 *drvopts = NULL;
569                 if (g_hash_table_size(drvargs) > 0) {
570                         if (!(*drvopts = hash_to_hwopt(drvargs))) {
571                                 /* Unknown options, already logged. */
572                                 g_hash_table_destroy(drvargs);
573                                 return FALSE;
574                         }
575                 }
576         }
577
578         g_hash_table_destroy(drvargs);
579
580         return TRUE;
581 }