runtc: Update to the new libsigrok session API.
[libsigrokdecode.git] / tests / runtc.c
1 /*
2  * This file is part of the libsigrokdecode project.
3  *
4  * Copyright (C) 2013 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 <Python.h>
21 #include "../libsigrokdecode.h"
22 #include <libsigrok/libsigrok.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <sys/time.h>
33 #include <sys/resource.h>
34 #include <dirent.h>
35 #include <glib.h>
36 #ifdef __LINUX__
37 #include <sched.h>
38 #endif
39 #include "config.h"
40
41 int debug = FALSE;
42 int statistics = FALSE;
43 char *coverage_report;
44
45 struct channel {
46         char *name;
47         int channel;
48 };
49
50 struct option {
51         char *key;
52         GVariant *value;
53 };
54
55 struct pd {
56         char *name;
57         GSList *channels;
58         GSList *options;
59 };
60
61 struct output {
62         char *pd;
63         int type;
64         char *class;
65         int class_idx;
66         char *outfile;
67         int outfd;
68 };
69
70 struct cvg {
71         int num_lines;
72         int num_missed;
73         float coverage;
74         GSList *missed_lines;
75 };
76
77
78 struct cvg *get_mod_cov(PyObject *py_cov, char *module_name);
79 void cvg_add(struct cvg *dst, struct cvg *src);
80 struct cvg *cvg_new(void);
81 gboolean find_missed_line(struct cvg *cvg, char *linespec);
82
83
84 static void logmsg(char *prefix, FILE *out, const char *format, va_list args)
85 {
86         if (prefix)
87                 fprintf(out, "%s", prefix);
88         vfprintf(out, format, args);
89         fprintf(out, "\n");
90 }
91
92 static void DBG(const char *format, ...)
93 {
94         va_list args;
95
96         if (!debug)
97                 return;
98         va_start(args, format);
99         logmsg("DBG: runtc: ", stdout, format, args);
100         va_end(args);
101 }
102
103 static void ERR(const char *format, ...)
104 {
105         va_list args;
106
107         va_start(args, format);
108         logmsg("Error: ", stderr, format, args);
109         va_end(args);
110 }
111
112 static int sr_log(void *cb_data, int loglevel, const char *format, va_list args)
113 {
114         (void)cb_data;
115
116         if (loglevel == SR_LOG_ERR || loglevel == SR_LOG_WARN)
117                 logmsg("Error: sr: ", stderr, format, args);
118         else if (debug)
119                 logmsg("DBG: sr: ", stdout, format, args);
120
121         return SRD_OK;
122 }
123
124 static int srd_log(void *cb_data, int loglevel, const char *format, va_list args)
125 {
126         (void)cb_data;
127
128         if (loglevel == SRD_LOG_ERR || loglevel == SRD_LOG_WARN)
129                 logmsg("Error: srd: ", stderr, format, args);
130         else if (debug)
131                 logmsg("DBG: srd: ", stdout, format, args);
132
133         return SRD_OK;
134 }
135
136 static void usage(char *msg)
137 {
138         if (msg)
139                 fprintf(stderr, "%s\n", msg);
140
141         printf("Usage: runtc [-dPpoiOf]\n");
142         printf("  -d  Debug\n");
143         printf("  -P  <protocol decoder>\n");
144         printf("  -p  <channelname=channelnum> (optional)\n");
145         printf("  -o  <channeloption=value> (optional)\n");
146         printf("  -i <input file>\n");
147         printf("  -O <output-pd:output-type[:output-class]>\n");
148         printf("  -f <output file> (optional)\n");
149         printf("  -c <coverage report> (optional)\n");
150         exit(msg ? 1 : 0);
151
152 }
153
154 /* This is a neutered version of libsigrokdecode's py_str_as_str(). It
155  * does no error checking, but then the only strings it processes are
156  * generated by Python's repr(), so are known good. */
157 static char *py_str_as_str(const PyObject *py_str)
158 {
159         PyObject *py_encstr;
160         char *str, *outstr;
161
162         py_encstr = PyUnicode_AsEncodedString((PyObject *)py_str, "utf-8", NULL);
163         str = PyBytes_AS_STRING(py_encstr);
164         outstr = g_strdup(str);
165         Py_DecRef(py_encstr);
166
167         return outstr;
168 }
169
170 static void srd_cb_py(struct srd_proto_data *pdata, void *cb_data)
171 {
172         struct output *op;
173         PyObject *pydata, *pyrepr;
174         GString *out;
175         char *s;
176
177         DBG("Python output from %s", pdata->pdo->di->inst_id);
178         op = cb_data;
179         pydata = pdata->data;
180         DBG("ptr %p", pydata);
181
182         if (strcmp(pdata->pdo->di->inst_id, op->pd))
183                 /* This is not the PD selected for output. */
184                 return;
185
186         if (!(pyrepr = PyObject_Repr(pydata))) {
187                 ERR("Invalid Python object.");
188                 return;
189         }
190         s = py_str_as_str(pyrepr);
191         Py_DecRef(pyrepr);
192
193         /* Output format for testing is '<ss>-<es> <inst-id>: <repr>\n' */
194         out = g_string_sized_new(128);
195         g_string_printf(out, "%"PRIu64"-%"PRIu64" %s: %s\n",
196                         pdata->start_sample, pdata->end_sample,
197                         pdata->pdo->di->inst_id, s);
198         g_free(s);
199         if (write(op->outfd, out->str, out->len) == -1)
200                 ERR("SRD_OUTPUT_PYTHON callback write failure!");
201         DBG("wrote '%s'", out->str);
202         g_string_free(out, TRUE);
203
204 }
205
206 static void srd_cb_bin(struct srd_proto_data *pdata, void *cb_data)
207 {
208         struct srd_proto_data_binary *pdb;
209         struct output *op;
210         GString *out;
211         unsigned int i;
212
213         DBG("Binary output from %s", pdata->pdo->di->inst_id);
214         op = cb_data;
215         pdb = pdata->data;
216
217         if (strcmp(pdata->pdo->di->inst_id, op->pd))
218                 /* This is not the PD selected for output. */
219                 return;
220
221         if (op->class_idx != -1 && op->class_idx != pdb->bin_class)
222                 /*
223                  * This output takes a specific binary class,
224                  * but not the one that just came in.
225                  */
226                 return;
227
228         out = g_string_sized_new(128);
229         g_string_printf(out, "%"PRIu64"-%"PRIu64" %s:",
230                         pdata->start_sample, pdata->end_sample,
231                         pdata->pdo->di->inst_id);
232         for (i = 0; i < pdb->size; i++) {
233                 g_string_append_printf(out, " %.2x", pdb->data[i]);
234         }
235         g_string_append(out, "\n");
236         if (write(op->outfd, out->str, out->len) == -1)
237                 ERR("SRD_OUTPUT_BINARY callback write failure!");
238
239 }
240
241 static void srd_cb_ann(struct srd_proto_data *pdata, void *cb_data)
242 {
243         struct srd_decoder *dec;
244         struct srd_proto_data_annotation *pda;
245         struct output *op;
246         GString *line;
247         int i;
248         char **dec_ann;
249
250         DBG("Annotation output from %s", pdata->pdo->di->inst_id);
251         op = cb_data;
252         pda = pdata->data;
253         dec = pdata->pdo->di->decoder;
254         if (strcmp(pdata->pdo->di->inst_id, op->pd))
255                 /* This is not the PD selected for output. */
256                 return;
257
258         if (op->class_idx != -1 && op->class_idx != pda->ann_format)
259                 /*
260                  * This output takes a specific annotation class,
261                  * but not the one that just came in.
262                  */
263                 return;
264
265         dec_ann = g_slist_nth_data(dec->annotations, pda->ann_format);
266         line = g_string_sized_new(256);
267         g_string_printf(line, "%"PRIu64"-%"PRIu64" %s: %s:",
268                         pdata->start_sample, pdata->end_sample,
269                         pdata->pdo->di->inst_id, dec_ann[0]);
270         for (i = 0; pda->ann_text[i]; i++)
271                 g_string_append_printf(line, " \"%s\"", pda->ann_text[i]);
272         g_string_append(line, "\n");
273         if (write(op->outfd, line->str, line->len) == -1)
274                 ERR("SRD_OUTPUT_ANN callback write failure!");
275         g_string_free(line, TRUE);
276
277 }
278
279 static void sr_cb(const struct sr_dev_inst *sdi,
280                 const struct sr_datafeed_packet *packet, void *cb_data)
281 {
282         const struct sr_datafeed_logic *logic;
283         struct srd_session *sess;
284         GVariant *gvar;
285         uint64_t samplerate;
286         int num_samples;
287         static int samplecnt = 0;
288
289         sess = cb_data;
290
291         switch (packet->type) {
292         case SR_DF_HEADER:
293                 DBG("Received SR_DF_HEADER");
294                 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
295                                 &gvar) != SR_OK) {
296                         ERR("Getting samplerate failed");
297                         break;
298                 }
299                 samplerate = g_variant_get_uint64(gvar);
300                 g_variant_unref(gvar);
301                 if (srd_session_metadata_set(sess, SRD_CONF_SAMPLERATE,
302                                 g_variant_new_uint64(samplerate)) != SRD_OK) {
303                         ERR("Setting samplerate failed");
304                         break;
305                 }
306                 if (srd_session_start(sess) != SRD_OK) {
307                         ERR("Session start failed");
308                         break;
309                 }
310                 break;
311         case SR_DF_LOGIC:
312                 logic = packet->payload;
313                 num_samples = logic->length / logic->unitsize;
314                 DBG("Received SR_DF_LOGIC: %d samples", num_samples);
315                 srd_session_send(sess, samplecnt, samplecnt + num_samples,
316                                 logic->data, logic->length);
317                 samplecnt += logic->length / logic->unitsize;
318                 break;
319         case SR_DF_END:
320                 DBG("Received SR_DF_END");
321                 break;
322         }
323
324 }
325
326 static int run_testcase(char *infile, GSList *pdlist, struct output *op)
327 {
328         struct srd_session *sess;
329         struct srd_decoder *dec;
330         struct srd_decoder_inst *di, *prev_di;
331         srd_pd_output_callback cb;
332         struct pd *pd;
333         struct channel *channel;
334         struct option *option;
335         GVariant *gvar;
336         GHashTable *channels, *opts;
337         GSList *pdl, *l;
338         int idx;
339         int max_channel;
340         char **decoder_class;
341         struct sr_session *sr_sess;
342
343         if (op->outfile) {
344                 if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
345                         ERR("Unable to open %s for writing: %s", op->outfile,
346                                         strerror(errno));
347                         return FALSE;
348                 }
349         }
350
351         if (sr_session_load(infile, &sr_sess) != SR_OK)
352                 return FALSE;
353
354         if (srd_session_new(&sess) != SRD_OK)
355                 return FALSE;
356         sr_session_datafeed_callback_add(sr_sess, sr_cb, sess);
357         switch (op->type) {
358         case SRD_OUTPUT_ANN:
359                 cb = srd_cb_ann;
360                 break;
361         case SRD_OUTPUT_BINARY:
362                 cb = srd_cb_bin;
363                 break;
364         case SRD_OUTPUT_PYTHON:
365                 cb = srd_cb_py;
366                 break;
367         default:
368                 return FALSE;
369         }
370         srd_pd_output_callback_add(sess, op->type, cb, op);
371
372         prev_di = NULL;
373         pd = NULL;
374         for (pdl = pdlist; pdl; pdl = pdl->next) {
375                 pd = pdl->data;
376                 if (srd_decoder_load(pd->name) != SRD_OK)
377                         return FALSE;
378
379                 /* Instantiate decoder and pass in options. */
380                 opts = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
381                                 (GDestroyNotify)g_variant_unref);
382                 for (l = pd->options; l; l = l->next) {
383                         option = l->data;
384                         g_hash_table_insert(opts, option->key, option->value);
385                 }
386                 if (!(di = srd_inst_new(sess, pd->name, opts)))
387                         return FALSE;
388                 g_hash_table_destroy(opts);
389
390                 /* Map channels. */
391                 if (pd->channels) {
392                         channels = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
393                                         (GDestroyNotify)g_variant_unref);
394                         max_channel = 0;
395                         for (l = pd->channels; l; l = l->next) {
396                                 channel = l->data;
397                                 if (channel->channel > max_channel)
398                                         max_channel = channel->channel;
399                                 gvar = g_variant_new_int32(channel->channel);
400                                 g_variant_ref_sink(gvar);
401                                 g_hash_table_insert(channels, channel->name, gvar);
402                         }
403                         if (srd_inst_channel_set_all(di, channels,
404                                         (max_channel + 8) / 8) != SRD_OK)
405                                 return FALSE;
406                         g_hash_table_destroy(channels);
407                 }
408
409                 /* If this is not the first decoder in the list, stack it
410                  * on top of the previous one. */
411                 if (prev_di) {
412                         if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
413                                 ERR("Failed to stack decoder instances.");
414                                 return FALSE;
415                         }
416                 }
417                 prev_di = di;
418         }
419
420         /* Resolve top decoder's class index, so we can match. */
421         dec = srd_decoder_get_by_id(pd->name);
422         if (op->class) {
423                 if (op->type == SRD_OUTPUT_ANN)
424                         l = dec->annotations;
425                 else if (op->type == SRD_OUTPUT_BINARY)
426                         l = dec->binary;
427                 else
428                         /* Only annotations and binary can have a class. */
429                         return FALSE;
430                 idx = 0;
431                 while (l) {
432                         decoder_class = l->data;
433                         if (!strcmp(decoder_class[0], op->class)) {
434                                 op->class_idx = idx;
435                                 break;
436                         } else
437                                 idx++;
438                         l = l->next;
439                 }
440                 if (op->class_idx == -1) {
441                         ERR("Output class '%s' not found in decoder %s.",
442                                         op->class, pd->name);
443                         return FALSE;
444                 } else
445                         DBG("Class %s index is %d", op->class, op->class_idx);
446         }
447
448         sr_session_start(sr_sess);
449         sr_session_run(sr_sess);
450         sr_session_stop(sr_sess);
451
452         srd_session_destroy(sess);
453
454         if (op->outfile)
455                 close(op->outfd);
456
457         return TRUE;
458 }
459
460 static PyObject *start_coverage(GSList *pdlist)
461 {
462         PyObject *py_mod, *py_pdlist, *py_pd, *py_func, *py_args, *py_kwargs, *py_cov;
463         GSList *l;
464         struct pd *pd;
465
466         DBG("Starting coverage.");
467
468         if (!(py_mod = PyImport_ImportModule("coverage")))
469                 return NULL;
470
471         if (!(py_pdlist = PyList_New(0)))
472                 return NULL;
473         for (l = pdlist; l; l = l->next) {
474                 pd = l->data;
475                 py_pd = PyUnicode_FromFormat("*/%s/*.py", pd->name);
476                 if (PyList_Append(py_pdlist, py_pd) < 0)
477                         return NULL;
478                 Py_DecRef(py_pd);
479         }
480         if (!(py_func = PyObject_GetAttrString(py_mod, "coverage")))
481                 return NULL;
482         if (!(py_args = PyTuple_New(0)))
483                 return NULL;
484         if (!(py_kwargs = Py_BuildValue("{sO}", "include", py_pdlist)))
485                 return NULL;
486         if (!(py_cov = PyObject_Call(py_func, py_args, py_kwargs)))
487                 return NULL;
488         if (!(PyObject_CallMethod(py_cov, "start", NULL)))
489                 return NULL;
490         Py_DecRef(py_pdlist);
491         Py_DecRef(py_args);
492         Py_DecRef(py_kwargs);
493         Py_DecRef(py_func);
494
495         return py_cov;
496 }
497
498 struct cvg *get_mod_cov(PyObject *py_cov, char *module_name)
499 {
500         PyObject *py_mod, *py_pathlist, *py_path, *py_func, *py_pd;
501         PyObject *py_result, *py_missed, *py_item;
502         DIR *d;
503         struct dirent *de;
504         struct cvg *cvg_mod;
505         int num_lines, num_missed, linenum, i, j;
506         char *path, *linespec;
507
508         if (!(py_mod = PyImport_ImportModule(module_name)))
509                 return NULL;
510
511         cvg_mod = NULL;
512         py_pathlist = PyObject_GetAttrString(py_mod, "__path__");
513         for (i = 0; i < PyList_Size(py_pathlist); i++) {
514                 py_path = PyList_GetItem(py_pathlist, i);
515         PyUnicode_FSConverter(PyList_GetItem(py_pathlist, i), &py_path);
516                 path = PyBytes_AS_STRING(py_path);
517                 if (!(d = opendir(path))) {
518                         ERR("Invalid module path '%s'", path);
519                         return NULL;
520                 }
521                 while ((de = readdir(d))) {
522                         if (strncmp(de->d_name + strlen(de->d_name) - 3, ".py", 3))
523                                 continue;
524
525                         if (!(py_func = PyObject_GetAttrString(py_cov, "analysis2")))
526                                 return NULL;
527                         if (!(py_pd = PyUnicode_FromFormat("%s/%s", path, de->d_name)))
528                                 return NULL;
529                         if (!(py_result = PyObject_CallFunction(py_func, "O", py_pd)))
530                                 return NULL;
531                         Py_DecRef(py_pd);
532                         Py_DecRef(py_func);
533
534                         if (!cvg_mod)
535                                 cvg_mod = cvg_new();
536                         if (PyTuple_Size(py_result) != 5) {
537                                 ERR("Invalid result from coverage of '%s/%s'", path, de->d_name);
538                                 return NULL;
539                         }
540                         num_lines = PyList_Size(PyTuple_GetItem(py_result, 1));
541                         py_missed = PyTuple_GetItem(py_result, 3);
542                         num_missed = PyList_Size(py_missed);
543                         cvg_mod->num_lines += num_lines;
544                         cvg_mod->num_missed += num_missed;
545                         for (j = 0; j < num_missed; j++) {
546                                 py_item = PyList_GetItem(py_missed, j);
547                                 linenum = PyLong_AsLong(py_item);
548                                 linespec = g_strdup_printf("%s/%s:%d", module_name,
549                                                 de->d_name, linenum);
550                                 cvg_mod->missed_lines = g_slist_append(cvg_mod->missed_lines, linespec);
551                         }
552                         DBG("Coverage for %s/%s: %d lines, %d missed.",
553                                         module_name, de->d_name, num_lines, num_missed);
554                         Py_DecRef(py_result);
555                 }
556         }
557         if (cvg_mod->num_lines)
558                 cvg_mod->coverage = 100 - ((float)cvg_mod->num_missed / (float)cvg_mod->num_lines * 100);
559
560         Py_DecRef(py_mod);
561     Py_DecRef(py_path);
562
563         return cvg_mod;
564 }
565
566 struct cvg *cvg_new(void)
567 {
568         struct cvg *cvg;
569
570         cvg = calloc(1, sizeof(struct cvg));
571
572         return cvg;
573 }
574
575 gboolean find_missed_line(struct cvg *cvg, char *linespec)
576 {
577         GSList *l;
578
579         for (l = cvg->missed_lines; l; l = l->next)
580                 if (!strcmp(l->data, linespec))
581                         return TRUE;
582
583         return FALSE;
584 }
585
586 void cvg_add(struct cvg *dst, struct cvg *src)
587 {
588         GSList *l;
589         char *linespec;
590
591
592         dst->num_lines += src->num_lines;
593         dst->num_missed += src->num_missed;
594         for (l = src->missed_lines; l; l = l->next) {
595                 linespec = l->data;
596                 if (!find_missed_line(dst, linespec))
597                         dst->missed_lines = g_slist_append(dst->missed_lines, linespec);
598         }
599
600 }
601
602 static int report_coverage(PyObject *py_cov, GSList *pdlist)
603 {
604         PyObject *py_func, *py_mod, *py_args, *py_kwargs, *py_outfile, *py_pct;
605         GSList *l, *ml;
606         struct pd *pd;
607         struct cvg *cvg_mod, *cvg_all;
608         float total_coverage;
609         int lines, missed, cnt;
610
611         DBG("Making coverage report.");
612
613         /* Get coverage for each module in the stack. */
614         lines = missed = 0;
615         cvg_all = cvg_new();
616         for (cnt = 0, l = pdlist; l; l = l->next, cnt++) {
617                 pd = l->data;
618                 if (!(cvg_mod = get_mod_cov(py_cov, pd->name)))
619                         return FALSE;
620                 printf("coverage: scope=%s coverage=%.0f%% lines=%d missed=%d "
621                                 "missed_lines=", pd->name, cvg_mod->coverage,
622                                 cvg_mod->num_lines, cvg_mod->num_missed);
623                 for (ml = cvg_mod->missed_lines; ml; ml = ml->next) {
624                         if (ml != cvg_mod->missed_lines)
625                                 printf(",");
626                         printf("%s", (char *)ml->data);
627                 }
628                 printf("\n");
629                 lines += cvg_mod->num_lines;
630                 missed += cvg_mod->num_missed;
631                 cvg_add(cvg_all, cvg_mod);
632                 DBG("Coverage for module %s: %d lines, %d missed", pd->name,
633                                 cvg_mod->num_lines, cvg_mod->num_missed);
634         }
635         lines /= cnt;
636         missed /= cnt;
637         total_coverage = 100 - ((float)missed / (float)lines * 100);
638
639         /* Machine-readable stats on stdout. */
640         printf("coverage: scope=all coverage=%.0f%% lines=%d missed=%d\n",
641                         total_coverage, cvg_all->num_lines, cvg_all->num_missed);
642
643
644         /* Write text report to file. */
645         /* io.open(coverage_report, "w") */
646         if (!(py_mod = PyImport_ImportModule("io")))
647                 return FALSE;
648         if (!(py_func = PyObject_GetAttrString(py_mod, "open")))
649                 return FALSE;
650         if (!(py_args = PyTuple_New(0)))
651                 return FALSE;
652         if (!(py_kwargs = Py_BuildValue("{ssss}", "file", coverage_report,
653                         "mode", "w")))
654                 return FALSE;
655         if (!(py_outfile = PyObject_Call(py_func, py_args, py_kwargs)))
656                 return FALSE;
657         Py_DecRef(py_kwargs);
658         Py_DecRef(py_func);
659
660         /* py_cov.report(file=py_outfile) */
661         if (!(py_func = PyObject_GetAttrString(py_cov, "report")))
662                 return FALSE;
663         if (!(py_kwargs = Py_BuildValue("{sO}", "file", py_outfile)))
664                 return FALSE;
665         if (!(py_pct = PyObject_Call(py_func, py_args, py_kwargs)))
666                 return FALSE;
667         Py_DecRef(py_pct);
668         Py_DecRef(py_kwargs);
669         Py_DecRef(py_func);
670
671         /* py_outfile.close() */
672         if (!(py_func = PyObject_GetAttrString(py_outfile, "close")))
673                 return FALSE;
674         if (!PyObject_Call(py_func, py_args, NULL))
675                 return FALSE;
676         Py_DecRef(py_outfile);
677         Py_DecRef(py_func);
678         Py_DecRef(py_args);
679         Py_DecRef(py_mod);
680
681         return TRUE;
682 }
683
684 int main(int argc, char **argv)
685 {
686         struct sr_context *ctx;
687         PyObject *coverage;
688         GSList *pdlist;
689         struct pd *pd;
690         struct channel *channel;
691         struct option *option;
692         struct output *op;
693         int ret, c;
694         char *opt_infile, **kv, **opstr;
695
696         op = malloc(sizeof(struct output));
697         op->pd = NULL;
698         op->type = -1;
699         op->class = NULL;
700         op->class_idx = -1;
701         op->outfd = 1;
702
703         pdlist = NULL;
704         opt_infile = NULL;
705         pd = NULL;
706         coverage = NULL;
707         while ((c = getopt(argc, argv, "dP:p:o:i:O:f:c:S")) != -1) {
708                 switch(c) {
709                 case 'd':
710                         debug = TRUE;
711                         break;
712                 case 'P':
713                         pd = g_malloc(sizeof(struct pd));
714                         pd->name = g_strdup(optarg);
715                         pd->channels = pd->options = NULL;
716                         pdlist = g_slist_append(pdlist, pd);
717                         break;
718                 case 'p':
719                 case 'o':
720                         if (g_slist_length(pdlist) == 0) {
721                                 /* No previous -P. */
722                                 ERR("Syntax error at '%s'", optarg);
723                                 usage(NULL);
724                         }
725                         kv = g_strsplit(optarg, "=", 0);
726                         if (!kv[0] || (!kv[1] || kv[2])) {
727                                 /* Need x=y. */
728                                 ERR("Syntax error at '%s'", optarg);
729                                 g_strfreev(kv);
730                                 usage(NULL);
731                         }
732                         if (c == 'p') {
733                                 channel = malloc(sizeof(struct channel));
734                                 channel->name = g_strdup(kv[0]);
735                                 channel->channel = strtoul(kv[1], 0, 10);
736                                 /* Apply to last PD. */
737                                 pd->channels = g_slist_append(pd->channels, channel);
738                         } else {
739                                 option = malloc(sizeof(struct option));
740                                 option->key = g_strdup(kv[0]);
741                                 option->value = g_variant_new_string(kv[1]);
742                 g_variant_ref_sink(option->value);
743                                 /* Apply to last PD. */
744                                 pd->options = g_slist_append(pd->options, option);
745                         }
746                         break;
747                 case 'i':
748                         opt_infile = optarg;
749                         break;
750                 case 'O':
751                         opstr = g_strsplit(optarg, ":", 0);
752                         if (!opstr[0] || !opstr[1]) {
753                                 /* Need at least abc:def. */
754                                 ERR("Syntax error at '%s'", optarg);
755                                 g_strfreev(opstr);
756                                 usage(NULL);
757                         }
758                         op->pd = g_strdup(opstr[0]);
759                         if (!strcmp(opstr[1], "annotation"))
760                                 op->type = SRD_OUTPUT_ANN;
761                         else if (!strcmp(opstr[1], "binary"))
762                                 op->type = SRD_OUTPUT_BINARY;
763                         else if (!strcmp(opstr[1], "python"))
764                                 op->type = SRD_OUTPUT_PYTHON;
765                         else if (!strcmp(opstr[1], "exception"))
766                 /* Doesn't matter, we just need it to bomb out. */
767                                 op->type = SRD_OUTPUT_PYTHON;
768                         else {
769                                 ERR("Unknown output type '%s'", opstr[1]);
770                                 g_strfreev(opstr);
771                                 usage(NULL);
772                         }
773                         if (opstr[2])
774                                 op->class = g_strdup(opstr[2]);
775                         g_strfreev(opstr);
776                         break;
777                 case 'f':
778                         op->outfile = g_strdup(optarg);
779                         op->outfd = -1;
780                         break;
781                 case 'c':
782                         coverage_report = optarg;
783                         break;
784                 case 'S':
785                         statistics = TRUE;
786                         break;
787                 default:
788                         usage(NULL);
789                 }
790         }
791         if (argc > optind)
792                 usage(NULL);
793         if (g_slist_length(pdlist) == 0)
794                 usage(NULL);
795         if (!opt_infile)
796                 usage(NULL);
797         if (!op->pd || op->type == -1)
798                 usage(NULL);
799
800         sr_log_callback_set(sr_log, NULL);
801         if (sr_init(&ctx) != SR_OK)
802                 return 1;
803
804         srd_log_callback_set(srd_log, NULL);
805         if (srd_init(DECODERS_DIR) != SRD_OK)
806                 return 1;
807
808         if (coverage_report) {
809                 if (!(coverage = start_coverage(pdlist))) {
810                         DBG("Failed to start coverage.");
811                         if (PyErr_Occurred()) {
812                                 PyErr_PrintEx(0);
813                                 PyErr_Clear();
814                         }
815                 }
816         }
817
818         ret = 0;
819         if (!run_testcase(opt_infile, pdlist, op))
820                 ret = 1;
821
822         if (coverage) {
823                 DBG("Stopping coverage.");
824
825                 if (!(PyObject_CallMethod(coverage, "stop", NULL)))
826                         ERR("Failed to stop coverage.");
827                 else if (!(report_coverage(coverage, pdlist)))
828                         ERR("Failed to make coverage report.");
829                 else
830                         DBG("Coverage report in %s", coverage_report);
831
832                 if (PyErr_Occurred()) {
833                         PyErr_PrintEx(0);
834                         PyErr_Clear();
835                 }
836                 Py_DecRef(coverage);
837         }
838
839         srd_exit();
840         sr_exit(ctx);
841
842         return ret;
843 }