cli: loose string comparison helper
[sigrok-cli.git] / sigrok-cli.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2012 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 <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <time.h>
26 #include <sys/time.h>
27 #include <inttypes.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <errno.h>
31 #include <glib.h>
32 #include <glib/gstdio.h>
33 #include <sigrok.h>
34 #include "sigrok-cli.h"
35 #include "config.h"
36
37 #define DEFAULT_OUTPUT_FORMAT "bits:width=64"
38
39 extern struct sr_hwcap_option sr_hwcap_options[];
40
41 static uint64_t limit_samples = 0;
42 static struct sr_output_format *output_format = NULL;
43 static int default_output_format = FALSE;
44 static char *output_format_param = NULL;
45 static char *input_format_param = NULL;
46 static GData *pd_ann_visible = NULL;
47
48 static gboolean opt_version = FALSE;
49 static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
50 static gboolean opt_list_devs = FALSE;
51 static gboolean opt_wait_trigger = FALSE;
52 static gchar *opt_input_file = NULL;
53 static gchar *opt_output_file = NULL;
54 static gchar *opt_dev = NULL;
55 static gchar *opt_probes = NULL;
56 static gchar *opt_triggers = NULL;
57 static gchar *opt_pds = NULL;
58 static gchar *opt_pd_stack = NULL;
59 static gchar *opt_input_format = NULL;
60 static gchar *opt_output_format = NULL;
61 static gchar *opt_time = NULL;
62 static gchar *opt_samples = NULL;
63 static gchar *opt_continuous = NULL;
64
65 static GOptionEntry optargs[] = {
66         {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
67                         "Show version and support list", NULL},
68         {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
69                         "Select libsigrok/libsigrokdecode loglevel", NULL},
70         {"list-devices", 'D', 0, G_OPTION_ARG_NONE, &opt_list_devs,
71                         "Scan for devices", NULL},
72         {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev,
73                         "Use specified device", NULL},
74         {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
75                         "Load input from file", NULL},
76         {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
77                         "Input format", NULL},
78         {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
79                         "Save output to file", NULL},
80         {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
81                         "Output format", NULL},
82         {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
83                         "Probes to use", NULL},
84         {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
85                         "Trigger configuration", NULL},
86         {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
87                         "Wait for trigger", NULL},
88         {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds,
89                         "Protocol decoders to run", NULL},
90         {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
91                         "Protocol decoder stack", NULL},
92         {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
93                         "How long to sample (ms)", NULL},
94         {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
95                         "Number of samples to acquire", NULL},
96         {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
97                         "Sample continuously", NULL},
98         {NULL, 0, 0, 0, NULL, NULL, NULL}
99 };
100
101 static void show_version(void)
102 {
103         GSList *l;
104         struct sr_dev_driver **drivers;
105         struct sr_input_format **inputs;
106         struct sr_output_format **outputs;
107         struct srd_decoder *dec;
108         int i;
109
110         printf("sigrok-cli %s\n\n", VERSION);
111
112         printf("Using libsigrok %s (lib version %s).\n",
113                sr_package_version_string_get(), sr_lib_version_string_get());
114         printf("Using libsigrokdecode %s (lib version %s).\n\n",
115                srd_package_version_string_get(), srd_lib_version_string_get());
116
117         printf("Supported hardware drivers:\n");
118         drivers = sr_driver_list();
119         for (i = 0; drivers[i]; i++) {
120                 printf("  %-20s %s\n", drivers[i]->name, drivers[i]->longname);
121         }
122         printf("\n");
123
124         printf("Supported input formats:\n");
125         inputs = sr_input_list();
126         for (i = 0; inputs[i]; i++)
127                 printf("  %-20s %s\n", inputs[i]->id, inputs[i]->description);
128         printf("\n");
129
130         printf("Supported output formats:\n");
131         outputs = sr_output_list();
132         for (i = 0; outputs[i]; i++)
133                 printf("  %-20s %s\n", outputs[i]->id, outputs[i]->description);
134         printf("\n");
135
136         if (srd_init(NULL) == SRD_OK) {
137                 printf("Supported protocol decoders:\n");
138                 srd_decoder_load_all();
139                 for (l = srd_decoder_list(); l; l = l->next) {
140                         dec = l->data;
141                         printf("  %-20s %s\n", dec->id, dec->longname);
142                         /* Print protocol description upon "-l 3" or higher. */
143                         if (opt_loglevel >= SR_LOG_INFO)
144                                 printf("  %-20s %s\n", "", dec->desc);
145                 }
146                 srd_exit();
147         }
148         printf("\n");
149 }
150
151 static void print_dev_line(const struct sr_dev *dev)
152 {
153         const struct sr_dev_inst *sdi;
154
155         sr_dev_info_get(dev, SR_DI_INST, (const void **)&sdi);
156
157         if (sdi->vendor && sdi->vendor[0])
158                 printf("%s ", sdi->vendor);
159         if (sdi->model && sdi->model[0])
160                 printf("%s ", sdi->model);
161         if (sdi->version && sdi->version[0])
162                 printf("%s ", sdi->version);
163         if (dev->probes)
164                 printf("with %d probes", g_slist_length(dev->probes));
165         printf("\n");
166 }
167
168 static void show_dev_list(void)
169 {
170         struct sr_dev *dev, *demo_dev;
171         GSList *devs, *l;
172         int devcnt;
173
174         devcnt = 0;
175         devs = sr_dev_list();
176
177         if (g_slist_length(devs) == 0)
178                 return;
179
180         printf("The following devices were found:\nID    Device\n");
181         demo_dev = NULL;
182         for (l = devs; l; l = l->next) {
183                 dev = l->data;
184                 if (sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV)) {
185                         demo_dev = dev;
186                         continue;
187                 }
188                 printf("%-3d   ", devcnt++);
189                 print_dev_line(dev);
190         }
191         if (demo_dev) {
192                 printf("demo  ");
193                 print_dev_line(demo_dev);
194         }
195 }
196
197 static void show_dev_detail(void)
198 {
199         struct sr_dev *dev;
200         struct sr_hwcap_option *hwo;
201         const struct sr_samplerates *samplerates;
202         int cap, *hwcaps, i;
203         char *s, *title;
204         const char *charopts, **stropts;
205
206         dev = parse_devstring(opt_dev);
207         if (!dev) {
208                 printf("No such device. Use -D to list all devices.\n");
209                 return;
210         }
211
212         print_dev_line(dev);
213
214         if (sr_dev_info_get(dev, SR_DI_TRIGGER_TYPES,
215                                         (const void **)&charopts) == SR_OK) {
216                 printf("Supported triggers: ");
217                 while (*charopts) {
218                         printf("%c ", *charopts);
219                         charopts++;
220                 }
221                 printf("\n");
222         }
223
224         title = "Supported options:\n";
225         hwcaps = dev->driver->hwcap_get_all();
226         for (cap = 0; hwcaps[cap]; cap++) {
227                 if (!(hwo = sr_hw_hwcap_get(hwcaps[cap])))
228                         continue;
229
230                 if (title) {
231                         printf("%s", title);
232                         title = NULL;
233                 }
234
235                 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
236                         printf("    %s", hwo->shortname);
237                         if (sr_dev_info_get(dev, SR_DI_PATTERNS,
238                                         (const void **)&stropts) == SR_OK) {
239                                 printf(" - supported patterns:\n");
240                                 for (i = 0; stropts[i]; i++)
241                                         printf("      %s\n", stropts[i]);
242                         } else {
243                                 printf("\n");
244                         }
245                 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
246                         printf("    %s", hwo->shortname);
247                         /* Supported samplerates */
248                         if (sr_dev_info_get(dev, SR_DI_SAMPLERATES,
249                                         (const void **)&samplerates) != SR_OK) {
250                                 printf("\n");
251                                 continue;
252                         }
253
254                         if (samplerates->step) {
255                                 /* low */
256                                 if (!(s = sr_samplerate_string(samplerates->low)))
257                                         continue;
258                                 printf(" (%s", s);
259                                 g_free(s);
260                                 /* high */
261                                 if (!(s = sr_samplerate_string(samplerates->high)))
262                                         continue;
263                                 printf(" - %s", s);
264                                 g_free(s);
265                                 /* step */
266                                 if (!(s = sr_samplerate_string(samplerates->step)))
267                                         continue;
268                                 printf(" in steps of %s)\n", s);
269                                 g_free(s);
270                         } else {
271                                 printf(" - supported samplerates:\n");
272                                 for (i = 0; samplerates->list[i]; i++) {
273                                         printf("      %s\n", sr_samplerate_string(samplerates->list[i]));
274                                 }
275                         }
276                 } else {
277                         printf("    %s\n", hwo->shortname);
278                 }
279         }
280 }
281
282 static void show_pd_detail(void)
283 {
284         GSList *l;
285         struct srd_decoder *dec;
286         char **pdtokens, **pdtok, **ann, *doc;
287         struct srd_probe *p;
288
289         pdtokens = g_strsplit(opt_pds, ",", -1);
290         for (pdtok = pdtokens; *pdtok; pdtok++) {
291                 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
292                         printf("Protocol decoder %s not found.\n", *pdtok);
293                         return;
294                 }
295                 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
296                                 dec->id, dec->name, dec->longname, dec->desc);
297                 printf("License: %s\n", dec->license);
298                 printf("Annotations:\n");
299                 if (dec->annotations) {
300                         for (l = dec->annotations; l; l = l->next) {
301                                 ann = l->data;
302                                 printf("- %s\n  %s\n", ann[0], ann[1]);
303                         }
304                 } else {
305                         printf("None.\n");
306                 }
307                 /* TODO: Print supported decoder options. */
308                 printf("Required probes:\n");
309                 if (dec->probes) {
310                         for (l = dec->probes; l; l = l->next) {
311                                 p = l->data;
312                                 printf("- %s (%s): %s\n",
313                                        p->name, p->id, p->desc);
314                         }
315                 } else {
316                         printf("None.\n");
317                 }
318                 printf("Optional probes:\n");
319                 if (dec->opt_probes) {
320                         for (l = dec->opt_probes; l; l = l->next) {
321                                 p = l->data;
322                                 printf("- %s (%s): %s\n",
323                                        p->name, p->id, p->desc);
324                         }
325                 } else {
326                         printf("None.\n");
327                 }
328                 if ((doc = srd_decoder_doc_get(dec))) {
329                         printf("Documentation:\n%s\n",
330                                doc[0] == '\n' ? doc + 1 : doc);
331                         g_free(doc);
332                 }
333         }
334
335         g_strfreev(pdtokens);
336 }
337
338 static void datafeed_in(struct sr_dev *dev, struct sr_datafeed_packet *packet)
339 {
340         static struct sr_output *o = NULL;
341         static int probelist[SR_MAX_NUM_PROBES + 1] = { 0 };
342         static uint64_t received_samples = 0;
343         static int unitsize = 0;
344         static int triggered = 0;
345         static FILE *outfile = NULL;
346         struct sr_probe *probe;
347         struct sr_datafeed_header *header;
348         struct sr_datafeed_logic *logic;
349         int num_enabled_probes, sample_size, ret, i;
350         uint64_t output_len, filter_out_len;
351         uint8_t *output_buf, *filter_out;
352
353         /* If the first packet to come in isn't a header, don't even try. */
354         if (packet->type != SR_DF_HEADER && o == NULL)
355                 return;
356
357         sample_size = -1;
358         switch (packet->type) {
359         case SR_DF_HEADER:
360                 g_debug("cli: Received SR_DF_HEADER");
361                 /* Initialize the output module. */
362                 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
363                         g_critical("Output module malloc failed.");
364                         exit(1);
365                 }
366                 o->format = output_format;
367                 o->dev = dev;
368                 o->param = output_format_param;
369                 if (o->format->init) {
370                         if (o->format->init(o) != SR_OK) {
371                                 g_critical("Output format initialization failed.");
372                                 exit(1);
373                         }
374                 }
375
376                 header = packet->payload;
377                 num_enabled_probes = 0;
378                 for (i = 0; i < header->num_logic_probes; i++) {
379                         probe = g_slist_nth_data(dev->probes, i);
380                         if (probe->enabled)
381                                 probelist[num_enabled_probes++] = probe->index;
382                 }
383                 /* How many bytes we need to store num_enabled_probes bits */
384                 unitsize = (num_enabled_probes + 7) / 8;
385
386                 outfile = stdout;
387                 if (opt_output_file) {
388                         if (default_output_format) {
389                                 /* output file is in session format, which means we'll
390                                  * dump everything in the datastore as it comes in,
391                                  * and save from there after the session. */
392                                 outfile = NULL;
393                                 ret = sr_datastore_new(unitsize, &(dev->datastore));
394                                 if (ret != SR_OK) {
395                                         g_critical("Failed to create datastore.");
396                                         exit(1);
397                                 }
398                         } else {
399                                 /* saving to a file in whatever format was set
400                                  * with -O, so all we need is a filehandle */
401                                 outfile = g_fopen(opt_output_file, "wb");
402                         }
403                 }
404                 if (opt_pds) {
405                         if (srd_session_start(num_enabled_probes, unitsize,
406                                         header->samplerate) != SRD_OK)
407                                 sr_session_halt();
408                 }
409                 break;
410         case SR_DF_END:
411                 g_debug("cli: Received SR_DF_END");
412                 if (!o) {
413                         g_debug("cli: double end!");
414                         break;
415                 }
416                 if (o->format->event) {
417                         o->format->event(o, SR_DF_END, &output_buf, &output_len);
418                         if (output_len) {
419                                 if (outfile)
420                                         fwrite(output_buf, 1, output_len, outfile);
421                                 g_free(output_buf);
422                                 output_len = 0;
423                         }
424                 }
425                 if (limit_samples && received_samples < limit_samples)
426                         g_warning("Device only sent %" PRIu64 " samples.",
427                                received_samples);
428                 if (opt_continuous)
429                         g_warning("Device stopped after %" PRIu64 " samples.",
430                                received_samples);
431                 sr_session_halt();
432                 if (outfile && outfile != stdout)
433                         fclose(outfile);
434                 g_free(o);
435                 o = NULL;
436                 break;
437         case SR_DF_TRIGGER:
438                 g_debug("cli: received SR_DF_TRIGGER");
439                 if (o->format->event)
440                         o->format->event(o, SR_DF_TRIGGER, &output_buf,
441                                          &output_len);
442                 triggered = 1;
443                 break;
444         case SR_DF_LOGIC:
445                 logic = packet->payload;
446                 sample_size = logic->unitsize;
447                 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
448                 break;
449         }
450
451         /* not supporting anything but SR_DF_LOGIC for now */
452
453         if (sample_size == -1 || logic->length == 0)
454                 return;
455
456         /* Don't store any samples until triggered. */
457         if (opt_wait_trigger && !triggered)
458                 return;
459
460         if (limit_samples && received_samples >= limit_samples)
461                 return;
462
463         /* TODO: filters only support SR_DF_LOGIC */
464         ret = sr_filter_probes(sample_size, unitsize, probelist,
465                                    logic->data, logic->length,
466                                    &filter_out, &filter_out_len);
467         if (ret != SR_OK)
468                 return;
469
470         /* what comes out of the filter is guaranteed to be packed into the
471          * minimum size needed to support the number of samples at this sample
472          * size. however, the driver may have submitted too much -- cut off
473          * the buffer of the last packet according to the sample limit.
474          */
475         if (limit_samples && (received_samples + logic->length / sample_size >
476                         limit_samples * sample_size))
477                 filter_out_len = limit_samples * sample_size - received_samples;
478
479         if (dev->datastore)
480                 sr_datastore_put(dev->datastore, filter_out,
481                                  filter_out_len, sample_size, probelist);
482
483         if (opt_output_file && default_output_format)
484                 /* saving to a session file, don't need to do anything else
485                  * to this data for now. */
486                 goto cleanup;
487
488         if (opt_pds) {
489                 if (srd_session_send(received_samples, (uint8_t*)filter_out,
490                                 filter_out_len) != SRD_OK)
491                         sr_session_halt();
492         } else {
493                 output_len = 0;
494                 if (o->format->data && packet->type == o->format->df_type)
495                         o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
496                 if (output_len) {
497                         fwrite(output_buf, 1, output_len, outfile);
498                         g_free(output_buf);
499                 }
500         }
501
502 cleanup:
503         g_free(filter_out);
504         received_samples += logic->length / sample_size;
505 }
506
507 /* Register the given PDs for this session.
508  * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
509  * That will instantiate two SPI decoders on the clock but different data
510  * lines.
511  */
512 static int register_pds(struct sr_dev *dev, const char *pdstring)
513 {
514         GHashTable *pd_opthash;
515         struct srd_decoder_inst *di;
516         char **pdtokens, **pdtok, *pd_name;
517
518         /* Avoid compiler warnings. */
519         (void)dev;
520
521         g_datalist_init(&pd_ann_visible);
522         pdtokens = g_strsplit(pdstring, ",", -1);
523         pd_opthash = NULL;
524         pd_name = NULL;
525
526         for (pdtok = pdtokens; *pdtok; pdtok++) {
527                 if (!(pd_opthash = parse_generic_arg(*pdtok))) {
528                         g_critical("Invalid protocol decoder option '%s'.", *pdtok);
529                         goto err_out;
530                 }
531
532                 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
533                 g_hash_table_remove(pd_opthash, "sigrok_key");
534                 if (srd_decoder_load(pd_name) != SRD_OK) {
535                         g_critical("Failed to load protocol decoder %s.", pd_name);
536                         goto err_out;
537                 }
538                 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
539                         g_critical("Failed to instantiate protocol decoder %s.", pd_name);
540                         goto err_out;
541                 }
542                 g_datalist_set_data(&pd_ann_visible, di->inst_id, pd_name);
543
544                 /* Any keys left in the options hash are probes, where the key
545                  * is the probe name as specified in the decoder class, and the
546                  * value is the probe number i.e. the order in which the PD's
547                  * incoming samples are arranged. */
548                 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK)
549                         goto err_out;
550                 g_hash_table_destroy(pd_opthash);
551                 pd_opthash = NULL;
552         }
553
554 err_out:
555         g_strfreev(pdtokens);
556         if (pd_opthash)
557                 g_hash_table_destroy(pd_opthash);
558         if (pd_name)
559                 g_free(pd_name);
560
561         return 0;
562 }
563
564 void show_pd_annotation(struct srd_proto_data *pdata, void *cb_data)
565 {
566         int i;
567         char **annotations;
568
569         /* 'cb_data' is not used in this specific callback. */
570         (void)cb_data;
571
572         if (pdata->ann_format != 0) {
573                 /* CLI only shows the default annotation format. */
574                 return;
575         }
576
577         if (!g_datalist_get_data(&pd_ann_visible, pdata->pdo->di->inst_id)) {
578                 /* Not in the list of PDs whose annotations we're showing. */
579                 return;
580         }
581
582         annotations = pdata->data;
583         if (opt_loglevel > SR_LOG_WARN)
584                 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
585         printf("%s: ", pdata->pdo->proto_id);
586         for (i = 0; annotations[i]; i++)
587                 printf("\"%s\" ", annotations[i]);
588         printf("\n");
589 }
590
591 static int select_probes(struct sr_dev *dev)
592 {
593         struct sr_probe *probe;
594         char **probelist;
595         int max_probes, i;
596
597         if (!opt_probes)
598                 return SR_OK;
599
600         /*
601          * This only works because a device by default initializes
602          * and enables all its probes.
603          */
604         max_probes = g_slist_length(dev->probes);
605         probelist = parse_probestring(max_probes, opt_probes);
606         if (!probelist) {
607                 return SR_ERR;
608         }
609
610         for (i = 0; i < max_probes; i++) {
611                 if (probelist[i]) {
612                         sr_dev_probe_name_set(dev, i + 1, probelist[i]);
613                         g_free(probelist[i]);
614                 } else {
615                         probe = sr_dev_probe_find(dev, i + 1);
616                         probe->enabled = FALSE;
617                 }
618         }
619         g_free(probelist);
620
621         return SR_OK;
622 }
623
624 /**
625  * Return the input file format which the CLI tool should use.
626  *
627  * If the user specified -I / --input-format, use that one. Otherwise, try to
628  * autodetect the format as good as possible. Failing that, return NULL.
629  *
630  * @param filename The filename of the input file. Must not be NULL.
631  * @param opt The -I / --input-file option the user specified (or NULL).
632  *
633  * @return A pointer to the 'struct sr_input_format' that should be used,
634  *         or NULL if no input format was selected or auto-detected.
635  */
636 static struct sr_input_format *determine_input_file_format(
637                         const char *filename, const char *opt)
638 {
639         int i;
640         struct sr_input_format **inputs;
641
642         /* If there are no input formats, return NULL right away. */
643         inputs = sr_input_list();
644         if (!inputs) {
645                 g_critical("No supported input formats available.");
646                 return NULL;
647         }
648
649         /* If the user specified -I / --input-format, use that one. */
650         if (opt) {
651                 for (i = 0; inputs[i]; i++) {
652                         if (strcasecmp(inputs[i]->id, opt_input_format))
653                                 continue;
654                         g_debug("Using user-specified input file format '%s'.",
655                                         inputs[i]->id);
656                         return inputs[i];
657                 }
658
659                 /* The user specified an unknown input format, return NULL. */
660                 g_critical("Error: specified input file format '%s' is "
661                         "unknown.", opt_input_format);
662                 return NULL;
663         }
664
665         /* Otherwise, try to find an input module that can handle this file. */
666         for (i = 0; inputs[i]; i++) {
667                 if (inputs[i]->format_match(filename))
668                         break;
669         }
670
671         /* Return NULL if no input module wanted to touch this. */
672         if (!inputs[i]) {
673                 g_critical("Error: no matching input module found.");
674                 return NULL;
675         }
676                 
677         return inputs[i];
678 }
679
680 static void load_input_file_format(void)
681 {
682         struct stat st;
683         struct sr_input *in;
684         struct sr_input_format *input_format;
685
686         if (!(input_format = determine_input_file_format(opt_input_file,
687                                                    opt_input_format)))
688                 /* The exact cause was already logged. */
689                 return;
690
691         if (stat(opt_input_file, &st) == -1) {
692                 g_critical("Failed to load %s: %s", opt_input_file,
693                         strerror(errno));
694                 exit(1);
695         }
696
697         /* Initialize the input module. */
698         if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
699                 g_critical("Failed to allocate input module.");
700                 exit(1);
701         }
702         in->format = input_format;
703         in->param = input_format_param;
704         if (in->format->init) {
705                 if (in->format->init(in) != SR_OK) {
706                         g_critical("Input format init failed.");
707                         exit(1);
708                 }
709         }
710
711         if (select_probes(in->vdev) > 0)
712             return;
713
714         sr_session_new();
715         sr_session_datafeed_callback_add(datafeed_in);
716         if (sr_session_dev_add(in->vdev) != SR_OK) {
717                 g_critical("Failed to use device.");
718                 sr_session_destroy();
719                 return;
720         }
721
722         input_format->loadfile(in, opt_input_file);
723         if (opt_output_file && default_output_format) {
724                 if (sr_session_save(opt_output_file) != SR_OK)
725                         g_critical("Failed to save session.");
726         }
727         sr_session_destroy();
728 }
729
730 static void load_input_file(void)
731 {
732
733         if (sr_session_load(opt_input_file) == SR_OK) {
734                 /* sigrok session file */
735                 sr_session_datafeed_callback_add(datafeed_in);
736                 sr_session_start();
737                 sr_session_run();
738                 sr_session_stop();
739         }
740         else {
741                 /* fall back on input modules */
742                 load_input_file_format();
743         }
744 }
745
746 int num_real_devs(void)
747 {
748         struct sr_dev *dev;
749         GSList *devs, *l;
750         int num_devs;
751
752         num_devs = 0;
753         devs = sr_dev_list();
754         for (l = devs; l; l = l->next) {
755                 dev = l->data;
756                 if (!sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV))
757                         num_devs++;
758         }
759
760         return num_devs;
761 }
762
763 static int set_dev_options(struct sr_dev *dev, GHashTable *args)
764 {
765         GHashTableIter iter;
766         gpointer key, value;
767         int ret, i;
768         uint64_t tmp_u64;
769         gboolean found;
770         gboolean tmp_bool;
771
772         g_hash_table_iter_init(&iter, args);
773         while (g_hash_table_iter_next(&iter, &key, &value)) {
774                 found = FALSE;
775                 for (i = 0; sr_hwcap_options[i].hwcap; i++) {
776                         if (strcmp(sr_hwcap_options[i].shortname, key))
777                                 continue;
778                         if ((value == NULL) && 
779                             (sr_hwcap_options[i].type != SR_T_BOOL)) {
780                                 g_critical("Option '%s' needs a value.", (char *)key);
781                                 return SR_ERR;
782                         }
783                         found = TRUE;
784                         switch (sr_hwcap_options[i].type) {
785                         case SR_T_UINT64:
786                                 ret = sr_parse_sizestring(value, &tmp_u64);
787                                 if (ret != SR_OK)
788                                         break;
789                                 ret = dev->driver->dev_config_set(dev->driver_index,
790                                         sr_hwcap_options[i].hwcap, &tmp_u64);
791                                 break;
792                         case SR_T_CHAR:
793                                 ret = dev->driver->dev_config_set(dev->driver_index,
794                                         sr_hwcap_options[i].hwcap, value);
795                                 break;
796                         case SR_T_BOOL:
797                                 if (!value)
798                                         tmp_bool = TRUE;
799                                 else 
800                                         tmp_bool = sr_parse_boolstring(value);
801                                 ret = dev->driver->dev_config_set(dev->driver_index,
802                                                 sr_hwcap_options[i].hwcap, 
803                                                 GINT_TO_POINTER(tmp_bool));
804                                 break;
805                         default:
806                                 ret = SR_ERR;
807                         }
808
809                         if (ret != SR_OK) {
810                                 g_critical("Failed to set device option '%s'.", (char *)key);
811                                 return ret;
812                         }
813                         else
814                                 break;
815                 }
816                 if (!found) {
817                         g_critical("Unknown device option '%s'.", (char *) key);
818                         return SR_ERR;
819                 }
820         }
821
822         return SR_OK;
823 }
824
825 static void run_session(void)
826 {
827         struct sr_dev *dev;
828         GHashTable *devargs;
829         int num_devs, max_probes, i;
830         uint64_t time_msec;
831         char **probelist, *devspec;
832
833         devargs = NULL;
834         if (opt_dev) {
835                 devargs = parse_generic_arg(opt_dev);
836                 devspec = g_hash_table_lookup(devargs, "sigrok_key");
837                 dev = parse_devstring(devspec);
838                 if (!dev) {
839                         g_critical("Device not found.");
840                         return;
841                 }
842                 g_hash_table_remove(devargs, "sigrok_key");
843         } else {
844                 num_devs = num_real_devs();
845                 if (num_devs == 1) {
846                         /* No device specified, but there is only one. */
847                         devargs = NULL;
848                         dev = parse_devstring("0");
849                 } else if (num_devs == 0) {
850                         g_critical("No devices found.");
851                         return;
852                 } else {
853                         g_critical("%d devices found, please select one.", num_devs);
854                         return;
855                 }
856         }
857
858         sr_session_new();
859         sr_session_datafeed_callback_add(datafeed_in);
860
861         if (sr_session_dev_add(dev) != SR_OK) {
862                 g_critical("Failed to use device.");
863                 sr_session_destroy();
864                 return;
865         }
866
867         if (devargs) {
868                 if (set_dev_options(dev, devargs) != SR_OK) {
869                         sr_session_destroy();
870                         return;
871                 }
872                 g_hash_table_destroy(devargs);
873         }
874
875         if (select_probes(dev) != SR_OK)
876             return;
877
878         if (opt_continuous) {
879                 if (!sr_driver_hwcap_exists(dev->driver, SR_HWCAP_CONTINUOUS)) {
880                         g_critical("This device does not support continuous sampling.");
881                         sr_session_destroy();
882                         return;
883                 }
884         }
885
886         if (opt_triggers) {
887                 probelist = sr_parse_triggerstring(dev, opt_triggers);
888                 if (!probelist) {
889                         sr_session_destroy();
890                         return;
891                 }
892
893                 max_probes = g_slist_length(dev->probes);
894                 for (i = 0; i < max_probes; i++) {
895                         if (probelist[i]) {
896                                 sr_dev_trigger_set(dev, i + 1, probelist[i]);
897                                 g_free(probelist[i]);
898                         }
899                 }
900                 g_free(probelist);
901         }
902
903         if (opt_time) {
904                 time_msec = sr_parse_timestring(opt_time);
905                 if (time_msec == 0) {
906                         g_critical("Invalid time '%s'", opt_time);
907                         sr_session_destroy();
908                         return;
909                 }
910
911                 if (sr_driver_hwcap_exists(dev->driver, SR_HWCAP_LIMIT_MSEC)) {
912                         if (dev->driver->dev_config_set(dev->driver_index,
913                             SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
914                                 g_critical("Failed to configure time limit.");
915                                 sr_session_destroy();
916                                 return;
917                         }
918                 }
919                 else {
920                         /* time limit set, but device doesn't support this...
921                          * convert to samples based on the samplerate.
922                          */
923                         limit_samples = 0;
924                         if (sr_dev_has_hwcap(dev, SR_HWCAP_SAMPLERATE)) {
925                                 const uint64_t *samplerate;
926
927                                 sr_dev_info_get(dev, SR_DI_CUR_SAMPLERATE,
928                                                 (const void **)&samplerate);
929                                 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
930                         }
931                         if (limit_samples == 0) {
932                                 g_critical("Not enough time at this samplerate.");
933                                 sr_session_destroy();
934                                 return;
935                         }
936
937                         if (dev->driver->dev_config_set(dev->driver_index,
938                             SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK) {
939                                 g_critical("Failed to configure time-based sample limit.");
940                                 sr_session_destroy();
941                                 return;
942                         }
943                 }
944         }
945
946         if (opt_samples) {
947                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
948                         || (dev->driver->dev_config_set(dev->driver_index,
949                             SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK)) {
950                         g_critical("Failed to configure sample limit.");
951                         sr_session_destroy();
952                         return;
953                 }
954         }
955
956         if (dev->driver->dev_config_set(dev->driver_index,
957                   SR_HWCAP_PROBECONFIG, (char *)dev->probes) != SR_OK) {
958                 g_critical("Failed to configure probes.");
959                 sr_session_destroy();
960                 return;
961         }
962
963         if (sr_session_start() != SR_OK) {
964                 g_critical("Failed to start session.");
965                 sr_session_destroy();
966                 return;
967         }
968
969         if (opt_continuous)
970                 add_anykey();
971
972         sr_session_run();
973
974         if (opt_continuous)
975                 clear_anykey();
976
977         if (opt_output_file && default_output_format) {
978                 if (sr_session_save(opt_output_file) != SR_OK)
979                         g_critical("Failed to save session.");
980         }
981         sr_session_destroy();
982 }
983
984 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
985                    const gchar *message, gpointer cb_data)
986 {
987         /* Avoid compiler warnings. */
988         (void)log_domain;
989         (void)cb_data;
990
991         /*
992          * All messages, warnings, errors etc. go to stderr (not stdout) in
993          * order to not mess up the CLI tool data output, e.g. VCD output.
994          */
995         if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
996                         || opt_loglevel > SR_LOG_WARN) {
997                 fprintf(stderr, "%s\n", message);
998                 fflush(stderr);
999         }
1000 }
1001
1002 int main(int argc, char **argv)
1003 {
1004         GOptionContext *context;
1005         GError *error;
1006         GHashTable *fmtargs;
1007         GHashTableIter iter;
1008         gpointer key, value;
1009         struct sr_output_format **outputs;
1010         struct srd_decoder_inst *di_from, *di_to;
1011         int i, ret;
1012         char *fmtspec, **pds;
1013
1014         g_log_set_default_handler(logger, NULL);
1015
1016         error = NULL;
1017         context = g_option_context_new(NULL);
1018         g_option_context_add_main_entries(context, optargs, NULL);
1019
1020         if (!g_option_context_parse(context, &argc, &argv, &error)) {
1021                 g_critical("%s", error->message);
1022                 return 1;
1023         }
1024
1025         /* Set the loglevel (amount of messages to output) for libsigrok. */
1026         if (sr_log_loglevel_set(opt_loglevel) != SR_OK) {
1027                 g_critical("sr_log_loglevel_set(%d) failed.", opt_loglevel);
1028                 return 1;
1029         }
1030
1031         /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1032         if (srd_log_loglevel_set(opt_loglevel) != SRD_OK) {
1033                 g_critical("srd_log_loglevel_set(%d) failed.", opt_loglevel);
1034                 return 1;
1035         }
1036
1037         if (sr_init() != SR_OK)
1038                 return 1;
1039
1040         if (opt_pds) {
1041                 if (srd_init(NULL) != SRD_OK) {
1042                         g_critical("Failed to initialize sigrokdecode.");
1043                         return 1;
1044                 }
1045                 if (register_pds(NULL, opt_pds) != 0) {
1046                         g_critical("Failed to register protocol decoders.");
1047                         return 1;
1048                 }
1049                 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1050                                 show_pd_annotation, NULL) != SRD_OK) {
1051                         g_critical("Failed to register protocol decoder callback.");
1052                         return 1;
1053                 }
1054
1055                 pds = g_strsplit(opt_pds, ",", 0);
1056                 if (g_strv_length(pds) > 1) {
1057                         if (opt_pd_stack) {
1058                                 /* A stack setup was specified, use that. */
1059                                 g_strfreev(pds);
1060                                 pds = g_strsplit(opt_pd_stack, ",", 0);
1061                                 if (g_strv_length(pds) < 2) {
1062                                         g_strfreev(pds);
1063                                         g_critical("Specify at least two protocol decoders to stack.");
1064                                         return 1;
1065                                 }
1066                         }
1067
1068                         if (!(di_from = srd_inst_find_by_id(pds[0]))) {
1069                                 g_critical("Cannot stack protocol decoder '%s': "
1070                                                 "instance not found.", pds[0]);
1071                                 return 1;
1072                         }
1073                         for (i = 1; pds[i]; i++) {
1074                                 if (!(di_to = srd_inst_find_by_id(pds[i]))) {
1075                                         g_critical("Cannot stack protocol decoder '%s': "
1076                                                         "instance not found.", pds[i]);
1077                                         return 1;
1078                                 }
1079                                 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
1080                                         return ret;
1081
1082                                 /* Don't show annotation from this PD. Only the last PD in
1083                                  * the stack will be left on the annotation list.
1084                                  */
1085                                 g_datalist_remove_data(&pd_ann_visible, di_from->inst_id);
1086
1087                                 di_from = di_to;
1088                         }
1089                 }
1090                 g_strfreev(pds);
1091         }
1092
1093         if (!opt_output_format) {
1094                 opt_output_format = DEFAULT_OUTPUT_FORMAT;
1095                 /* we'll need to remember this so when saving to a file
1096                  * later, sigrok session format will be used.
1097                  */
1098                 default_output_format = TRUE;
1099         }
1100         fmtargs = parse_generic_arg(opt_output_format);
1101         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1102         if (!fmtspec) {
1103                 g_critical("Invalid output format.");
1104                 return 1;
1105         }
1106         outputs = sr_output_list();
1107         for (i = 0; outputs[i]; i++) {
1108                 if (strcmp(outputs[i]->id, fmtspec))
1109                         continue;
1110                 g_hash_table_remove(fmtargs, "sigrok_key");
1111                 output_format = outputs[i];
1112                 g_hash_table_iter_init(&iter, fmtargs);
1113                 while (g_hash_table_iter_next(&iter, &key, &value)) {
1114                         /* only supporting one parameter per output module
1115                          * for now, and only its value */
1116                         output_format_param = g_strdup(value);
1117                         break;
1118                 }
1119                 break;
1120         }
1121         if (!output_format) {
1122                 g_critical("Invalid output format %s.", opt_output_format);
1123                 return 1;
1124         }
1125
1126         if (opt_version)
1127                 show_version();
1128         else if (opt_list_devs)
1129                 show_dev_list();
1130         else if (opt_input_file)
1131                 load_input_file();
1132         else if (opt_samples || opt_time || opt_continuous)
1133                 run_session();
1134         else if (opt_dev)
1135                 show_dev_detail();
1136         else if (opt_pds)
1137                 show_pd_detail();
1138         else
1139                 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1140
1141         if (opt_pds)
1142                 srd_exit();
1143
1144         g_option_context_free(context);
1145         g_hash_table_destroy(fmtargs);
1146         sr_exit();
1147
1148         return 0;
1149 }