]> sigrok.org Git - sigrok-test.git/blob - decoder/runtc.c
nunchuk: Add a few test-cases.
[sigrok-test.git] / decoder / runtc.c
1 /*
2  * This file is part of the sigrok-test 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/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
40 static int debug = FALSE;
41 static int statistics = FALSE;
42 static char *coverage_report;
43 static struct sr_context *ctx;
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         const char *name;
57         GSList *channels;
58         GSList *options;
59 };
60
61 struct output {
62         const char *pd;
63         int type;
64         const char *class;
65         int class_idx;
66         const 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 static struct cvg *get_mod_cov(PyObject *py_cov, const char *module_name);
78 static void cvg_add(struct cvg *dst, const struct cvg *src);
79 static struct cvg *cvg_new(void);
80 static gboolean find_missed_line(struct cvg *cvg, const char *linespec);
81
82 static void logmsg(const char *prefix, FILE *out, const char *format, va_list args)
83 {
84         if (prefix)
85                 fprintf(out, "%s", prefix);
86         vfprintf(out, format, args);
87         fprintf(out, "\n");
88 }
89
90 static void DBG(const char *format, ...)
91 {
92         va_list args;
93
94         if (!debug)
95                 return;
96         va_start(args, format);
97         logmsg("DBG: runtc: ", stdout, format, args);
98         va_end(args);
99 }
100
101 static void ERR(const char *format, ...)
102 {
103         va_list args;
104
105         va_start(args, format);
106         logmsg("Error: ", stderr, format, args);
107         va_end(args);
108 }
109
110 static int sr_log(void *cb_data, int loglevel, const char *format, va_list args)
111 {
112         (void)cb_data;
113
114         if (loglevel == SR_LOG_ERR || loglevel == SR_LOG_WARN)
115                 logmsg("Error: sr: ", stderr, format, args);
116         else if (debug)
117                 logmsg("DBG: sr: ", stdout, format, args);
118
119         return SRD_OK;
120 }
121
122 static int srd_log(void *cb_data, int loglevel, const char *format, va_list args)
123 {
124         (void)cb_data;
125
126         if (loglevel == SRD_LOG_ERR || loglevel == SRD_LOG_WARN)
127                 logmsg("Error: srd: ", stderr, format, args);
128         else if (debug)
129                 logmsg("DBG: srd: ", stdout, format, args);
130
131         return SRD_OK;
132 }
133
134 static void usage(const char *msg)
135 {
136         if (msg)
137                 fprintf(stderr, "%s\n", msg);
138
139         printf("Usage: runtc [-dPpoiOf]\n");
140         printf("  -d  Debug\n");
141         printf("  -P  <protocol decoder>\n");
142         printf("  -p  <channelname=channelnum> (optional)\n");
143         printf("  -o  <channeloption=value> (optional)\n");
144         printf("  -i <input file>\n");
145         printf("  -O <output-pd:output-type[:output-class]>\n");
146         printf("  -f <output file> (optional)\n");
147         printf("  -c <coverage report> (optional)\n");
148         exit(msg ? 1 : 0);
149
150 }
151
152 /*
153  * This is a neutered version of libsigrokdecode's py_str_as_str(). It
154  * does no error checking, but then the only strings it processes are
155  * generated by Python's repr(), so are known good.
156  */
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_class)
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_class);
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         struct sr_dev_driver *driver;
289
290         sess = cb_data;
291
292         driver = sr_dev_inst_driver_get(sdi);
293
294         switch (packet->type) {
295         case SR_DF_HEADER:
296                 DBG("Received SR_DF_HEADER");
297                 if (sr_config_get(driver, sdi, NULL, SR_CONF_SAMPLERATE,
298                                 &gvar) != SR_OK) {
299                         ERR("Getting samplerate failed");
300                         break;
301                 }
302                 samplerate = g_variant_get_uint64(gvar);
303                 g_variant_unref(gvar);
304                 if (srd_session_metadata_set(sess, SRD_CONF_SAMPLERATE,
305                                 g_variant_new_uint64(samplerate)) != SRD_OK) {
306                         ERR("Setting samplerate failed");
307                         break;
308                 }
309                 if (srd_session_start(sess) != SRD_OK) {
310                         ERR("Session start failed");
311                         break;
312                 }
313                 break;
314         case SR_DF_LOGIC:
315                 logic = packet->payload;
316                 num_samples = logic->length / logic->unitsize;
317                 DBG("Received SR_DF_LOGIC (%"PRIu64" bytes, unitsize = %d).",
318                         logic->length, logic->unitsize);
319                 srd_session_send(sess, samplecnt, samplecnt + num_samples,
320                                 logic->data, logic->length, logic->unitsize);
321                 samplecnt += logic->length / logic->unitsize;
322                 break;
323         case SR_DF_END:
324                 DBG("Received SR_DF_END");
325                 break;
326         }
327
328 }
329
330 static int run_testcase(const char *infile, GSList *pdlist, struct output *op)
331 {
332         struct srd_session *sess;
333         struct srd_decoder *dec;
334         struct srd_decoder_inst *di, *prev_di;
335         srd_pd_output_callback cb;
336         struct pd *pd;
337         struct channel *channel;
338         struct option *option;
339         GVariant *gvar;
340         GHashTable *channels, *opts;
341         GSList *pdl, *l, *devices;
342         int idx, i;
343         int max_channel;
344         char **decoder_class;
345         struct sr_session *sr_sess;
346         gboolean is_number;
347         const char *s;
348
349         if (op->outfile) {
350                 if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
351                         ERR("Unable to open %s for writing: %s", op->outfile,
352                                         strerror(errno));
353                         return FALSE;
354                 }
355         }
356
357         if (sr_session_load(ctx, infile, &sr_sess) != SR_OK)
358                 return FALSE;
359
360         sr_session_dev_list(sr_sess, &devices);
361
362         if (srd_session_new(&sess) != SRD_OK)
363                 return FALSE;
364         sr_session_datafeed_callback_add(sr_sess, sr_cb, sess);
365         switch (op->type) {
366         case SRD_OUTPUT_ANN:
367                 cb = srd_cb_ann;
368                 break;
369         case SRD_OUTPUT_BINARY:
370                 cb = srd_cb_bin;
371                 break;
372         case SRD_OUTPUT_PYTHON:
373                 cb = srd_cb_py;
374                 break;
375         default:
376                 return FALSE;
377         }
378         srd_pd_output_callback_add(sess, op->type, cb, op);
379
380         prev_di = NULL;
381         pd = NULL;
382         for (pdl = pdlist; pdl; pdl = pdl->next) {
383                 pd = pdl->data;
384                 if (srd_decoder_load(pd->name) != SRD_OK)
385                         return FALSE;
386
387                 /* Instantiate decoder and pass in options. */
388                 opts = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
389                                 (GDestroyNotify)g_variant_unref);
390                 for (l = pd->options; l; l = l->next) {
391                         option = l->data;
392
393                         is_number = TRUE;
394                         s = g_variant_get_string(option->value, NULL);
395                         for (i = 0; i < (int)strlen(s); i++) {
396                                 if (!isdigit(s[i]))
397                                         is_number = FALSE;
398                         }
399
400                         if (is_number) {
401                                 /* Integer option value */
402                                 g_hash_table_insert(opts, option->key,
403                                   g_variant_new_int64(strtoull(s, NULL, 10)));
404                         } else {
405                                 /* String option value */
406                                 g_hash_table_insert(opts, option->key, option->value);
407                         }
408                 }
409                 if (!(di = srd_inst_new(sess, pd->name, opts)))
410                         return FALSE;
411                 g_hash_table_destroy(opts);
412
413                 /* Map channels. */
414                 if (pd->channels) {
415                         channels = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
416                                         (GDestroyNotify)g_variant_unref);
417                         max_channel = 0;
418                         for (l = pd->channels; l; l = l->next) {
419                                 channel = l->data;
420                                 if (channel->channel > max_channel)
421                                         max_channel = channel->channel;
422                                 gvar = g_variant_new_int32(channel->channel);
423                                 g_variant_ref_sink(gvar);
424                                 g_hash_table_insert(channels, channel->name, gvar);
425                         }
426
427                         if (srd_inst_channel_set_all(di, channels) != SRD_OK)
428                                 return FALSE;
429                         g_hash_table_destroy(channels);
430                 }
431
432                 /*
433                  * If this is not the first decoder in the list, stack it
434                  * on top of the previous one.
435                  */
436                 if (prev_di) {
437                         if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
438                                 ERR("Failed to stack decoder instances.");
439                                 return FALSE;
440                         }
441                 }
442                 prev_di = di;
443         }
444
445         /* Resolve top decoder's class index, so we can match. */
446         dec = srd_decoder_get_by_id(pd->name);
447         if (op->class) {
448                 if (op->type == SRD_OUTPUT_ANN)
449                         l = dec->annotations;
450                 else if (op->type == SRD_OUTPUT_BINARY)
451                         l = dec->binary;
452                 else
453                         /* Only annotations and binary can have a class. */
454                         return FALSE;
455                 idx = 0;
456                 while (l) {
457                         decoder_class = l->data;
458                         if (!strcmp(decoder_class[0], op->class)) {
459                                 op->class_idx = idx;
460                                 break;
461                         } else
462                                 idx++;
463                         l = l->next;
464                 }
465                 if (op->class_idx == -1) {
466                         ERR("Output class '%s' not found in decoder %s.",
467                                         op->class, pd->name);
468                         return FALSE;
469                 } else
470                         DBG("Class %s index is %d", op->class, op->class_idx);
471         }
472
473         sr_session_start(sr_sess);
474         sr_session_run(sr_sess);
475         sr_session_stop(sr_sess);
476
477         srd_session_destroy(sess);
478
479         if (op->outfile)
480                 close(op->outfd);
481
482         return TRUE;
483 }
484
485 static PyObject *start_coverage(GSList *pdlist)
486 {
487         PyObject *py_mod, *py_pdlist, *py_pd, *py_func, *py_args, *py_kwargs, *py_cov;
488         GSList *l;
489         struct pd *pd;
490
491         DBG("Starting coverage.");
492
493         if (!(py_mod = PyImport_ImportModule("coverage")))
494                 return NULL;
495
496         if (!(py_pdlist = PyList_New(0)))
497                 return NULL;
498         for (l = pdlist; l; l = l->next) {
499                 pd = l->data;
500                 py_pd = PyUnicode_FromFormat("*/%s/*.py", pd->name);
501                 if (PyList_Append(py_pdlist, py_pd) < 0)
502                         return NULL;
503                 Py_DecRef(py_pd);
504         }
505         if (!(py_func = PyObject_GetAttrString(py_mod, "coverage")))
506                 return NULL;
507         if (!(py_args = PyTuple_New(0)))
508                 return NULL;
509         if (!(py_kwargs = Py_BuildValue("{sO}", "include", py_pdlist)))
510                 return NULL;
511         if (!(py_cov = PyObject_Call(py_func, py_args, py_kwargs)))
512                 return NULL;
513         if (!(PyObject_CallMethod(py_cov, "start", NULL)))
514                 return NULL;
515         Py_DecRef(py_pdlist);
516         Py_DecRef(py_args);
517         Py_DecRef(py_kwargs);
518         Py_DecRef(py_func);
519
520         return py_cov;
521 }
522
523 static struct cvg *get_mod_cov(PyObject *py_cov, const char *module_name)
524 {
525         PyObject *py_mod, *py_pathlist, *py_path, *py_func, *py_pd;
526         PyObject *py_result, *py_missed, *py_item;
527         DIR *d;
528         struct dirent *de;
529         struct cvg *cvg_mod;
530         int num_lines, num_missed, linenum, i, j;
531         char *path, *linespec;
532
533         if (!(py_mod = PyImport_ImportModule(module_name)))
534                 return NULL;
535
536         cvg_mod = NULL;
537         py_pathlist = PyObject_GetAttrString(py_mod, "__path__");
538         for (i = 0; i < PyList_Size(py_pathlist); i++) {
539                 py_path = PyList_GetItem(py_pathlist, i);
540                 PyUnicode_FSConverter(PyList_GetItem(py_pathlist, i), &py_path);
541                 path = PyBytes_AS_STRING(py_path);
542                 if (!(d = opendir(path))) {
543                         ERR("Invalid module path '%s'", path);
544                         return NULL;
545                 }
546                 while ((de = readdir(d))) {
547                         if (strncmp(de->d_name + strlen(de->d_name) - 3, ".py", 3))
548                                 continue;
549
550                         if (!(py_func = PyObject_GetAttrString(py_cov, "analysis2")))
551                                 return NULL;
552                         if (!(py_pd = PyUnicode_FromFormat("%s/%s", path, de->d_name)))
553                                 return NULL;
554                         if (!(py_result = PyObject_CallFunction(py_func, "O", py_pd)))
555                                 return NULL;
556                         Py_DecRef(py_pd);
557                         Py_DecRef(py_func);
558
559                         if (!cvg_mod)
560                                 cvg_mod = cvg_new();
561                         if (PyTuple_Size(py_result) != 5) {
562                                 ERR("Invalid result from coverage of '%s/%s'", path, de->d_name);
563                                 return NULL;
564                         }
565                         num_lines = PyList_Size(PyTuple_GetItem(py_result, 1));
566                         py_missed = PyTuple_GetItem(py_result, 3);
567                         num_missed = PyList_Size(py_missed);
568                         cvg_mod->num_lines += num_lines;
569                         cvg_mod->num_missed += num_missed;
570                         for (j = 0; j < num_missed; j++) {
571                                 py_item = PyList_GetItem(py_missed, j);
572                                 linenum = PyLong_AsLong(py_item);
573                                 linespec = g_strdup_printf("%s/%s:%d", module_name,
574                                                 de->d_name, linenum);
575                                 cvg_mod->missed_lines = g_slist_append(cvg_mod->missed_lines, linespec);
576                         }
577                         DBG("Coverage for %s/%s: %d lines, %d missed.",
578                                         module_name, de->d_name, num_lines, num_missed);
579                         Py_DecRef(py_result);
580                 }
581         }
582         if (cvg_mod->num_lines)
583                 cvg_mod->coverage = 100 - ((float)cvg_mod->num_missed / (float)cvg_mod->num_lines * 100);
584
585         Py_DecRef(py_mod);
586         Py_DecRef(py_path);
587
588         return cvg_mod;
589 }
590
591 static struct cvg *cvg_new(void)
592 {
593         struct cvg *cvg;
594
595         cvg = calloc(1, sizeof(struct cvg));
596
597         return cvg;
598 }
599
600 static gboolean find_missed_line(struct cvg *cvg, const char *linespec)
601 {
602         GSList *l;
603
604         for (l = cvg->missed_lines; l; l = l->next)
605                 if (!strcmp(l->data, linespec))
606                         return TRUE;
607
608         return FALSE;
609 }
610
611 static void cvg_add(struct cvg *dst, const struct cvg *src)
612 {
613         GSList *l;
614         char *linespec;
615
616         dst->num_lines += src->num_lines;
617         dst->num_missed += src->num_missed;
618         for (l = src->missed_lines; l; l = l->next) {
619                 linespec = l->data;
620                 if (!find_missed_line(dst, linespec))
621                         dst->missed_lines = g_slist_append(dst->missed_lines, linespec);
622         }
623
624 }
625
626 static int report_coverage(PyObject *py_cov, GSList *pdlist)
627 {
628         PyObject *py_func, *py_mod, *py_args, *py_kwargs, *py_outfile, *py_pct;
629         GSList *l, *ml;
630         struct pd *pd;
631         struct cvg *cvg_mod, *cvg_all;
632         float total_coverage;
633         int lines, missed, cnt;
634
635         DBG("Making coverage report.");
636
637         /* Get coverage for each module in the stack. */
638         lines = missed = 0;
639         cvg_all = cvg_new();
640         for (cnt = 0, l = pdlist; l; l = l->next, cnt++) {
641                 pd = l->data;
642                 if (!(cvg_mod = get_mod_cov(py_cov, pd->name)))
643                         return FALSE;
644                 printf("coverage: scope=%s coverage=%.0f%% lines=%d missed=%d "
645                                 "missed_lines=", pd->name, cvg_mod->coverage,
646                                 cvg_mod->num_lines, cvg_mod->num_missed);
647                 for (ml = cvg_mod->missed_lines; ml; ml = ml->next) {
648                         if (ml != cvg_mod->missed_lines)
649                                 printf(",");
650                         printf("%s", (char *)ml->data);
651                 }
652                 printf("\n");
653                 lines += cvg_mod->num_lines;
654                 missed += cvg_mod->num_missed;
655                 cvg_add(cvg_all, cvg_mod);
656                 DBG("Coverage for module %s: %d lines, %d missed", pd->name,
657                                 cvg_mod->num_lines, cvg_mod->num_missed);
658         }
659         lines /= cnt;
660         missed /= cnt;
661         total_coverage = 100 - ((float)missed / (float)lines * 100);
662
663         /* Machine-readable stats on stdout. */
664         printf("coverage: scope=all coverage=%.0f%% lines=%d missed=%d\n",
665                         total_coverage, cvg_all->num_lines, cvg_all->num_missed);
666
667         /* Write text report to file. */
668         /* io.open(coverage_report, "w") */
669         if (!(py_mod = PyImport_ImportModule("io")))
670                 return FALSE;
671         if (!(py_func = PyObject_GetAttrString(py_mod, "open")))
672                 return FALSE;
673         if (!(py_args = PyTuple_New(0)))
674                 return FALSE;
675         if (!(py_kwargs = Py_BuildValue("{ssss}", "file", coverage_report,
676                         "mode", "w")))
677                 return FALSE;
678         if (!(py_outfile = PyObject_Call(py_func, py_args, py_kwargs)))
679                 return FALSE;
680         Py_DecRef(py_kwargs);
681         Py_DecRef(py_func);
682
683         /* py_cov.report(file=py_outfile) */
684         if (!(py_func = PyObject_GetAttrString(py_cov, "report")))
685                 return FALSE;
686         if (!(py_kwargs = Py_BuildValue("{sO}", "file", py_outfile)))
687                 return FALSE;
688         if (!(py_pct = PyObject_Call(py_func, py_args, py_kwargs)))
689                 return FALSE;
690         Py_DecRef(py_pct);
691         Py_DecRef(py_kwargs);
692         Py_DecRef(py_func);
693
694         /* py_outfile.close() */
695         if (!(py_func = PyObject_GetAttrString(py_outfile, "close")))
696                 return FALSE;
697         if (!PyObject_Call(py_func, py_args, NULL))
698                 return FALSE;
699         Py_DecRef(py_outfile);
700         Py_DecRef(py_func);
701         Py_DecRef(py_args);
702         Py_DecRef(py_mod);
703
704         return TRUE;
705 }
706
707 int main(int argc, char **argv)
708 {
709         PyObject *coverage;
710         GSList *pdlist;
711         struct pd *pd;
712         struct channel *channel;
713         struct option *option;
714         struct output *op;
715         int ret, c;
716         char *opt_infile, **kv, **opstr;
717
718         op = malloc(sizeof(struct output));
719         op->pd = NULL;
720         op->type = -1;
721         op->class = NULL;
722         op->class_idx = -1;
723         op->outfd = 1;
724
725         pdlist = NULL;
726         opt_infile = NULL;
727         pd = NULL;
728         coverage = NULL;
729         while ((c = getopt(argc, argv, "dP:p:o:i:O:f:c:S")) != -1) {
730                 switch (c) {
731                 case 'd':
732                         debug = TRUE;
733                         break;
734                 case 'P':
735                         pd = g_malloc(sizeof(struct pd));
736                         pd->name = g_strdup(optarg);
737                         pd->channels = pd->options = NULL;
738                         pdlist = g_slist_append(pdlist, pd);
739                         break;
740                 case 'p':
741                 case 'o':
742                         if (g_slist_length(pdlist) == 0) {
743                                 /* No previous -P. */
744                                 ERR("Syntax error at '%s'", optarg);
745                                 usage(NULL);
746                         }
747                         kv = g_strsplit(optarg, "=", 0);
748                         if (!kv[0] || (!kv[1] || kv[2])) {
749                                 /* Need x=y. */
750                                 ERR("Syntax error at '%s'", optarg);
751                                 g_strfreev(kv);
752                                 usage(NULL);
753                         }
754                         if (c == 'p') {
755                                 channel = malloc(sizeof(struct channel));
756                                 channel->name = g_strdup(kv[0]);
757                                 channel->channel = strtoul(kv[1], 0, 10);
758                                 /* Apply to last PD. */
759                                 pd->channels = g_slist_append(pd->channels, channel);
760                         } else {
761                                 option = malloc(sizeof(struct option));
762                                 option->key = g_strdup(kv[0]);
763                                 option->value = g_variant_new_string(kv[1]);
764                 g_variant_ref_sink(option->value);
765                                 /* Apply to last PD. */
766                                 pd->options = g_slist_append(pd->options, option);
767                         }
768                         break;
769                 case 'i':
770                         opt_infile = optarg;
771                         break;
772                 case 'O':
773                         opstr = g_strsplit(optarg, ":", 0);
774                         if (!opstr[0] || !opstr[1]) {
775                                 /* Need at least abc:def. */
776                                 ERR("Syntax error at '%s'", optarg);
777                                 g_strfreev(opstr);
778                                 usage(NULL);
779                         }
780                         op->pd = g_strdup(opstr[0]);
781                         if (!strcmp(opstr[1], "annotation"))
782                                 op->type = SRD_OUTPUT_ANN;
783                         else if (!strcmp(opstr[1], "binary"))
784                                 op->type = SRD_OUTPUT_BINARY;
785                         else if (!strcmp(opstr[1], "python"))
786                                 op->type = SRD_OUTPUT_PYTHON;
787                         else if (!strcmp(opstr[1], "exception"))
788                                 /* Doesn't matter, we just need it to bomb out. */
789                                 op->type = SRD_OUTPUT_PYTHON;
790                         else {
791                                 ERR("Unknown output type '%s'", opstr[1]);
792                                 g_strfreev(opstr);
793                                 usage(NULL);
794                         }
795                         if (opstr[2])
796                                 op->class = g_strdup(opstr[2]);
797                         g_strfreev(opstr);
798                         break;
799                 case 'f':
800                         op->outfile = g_strdup(optarg);
801                         op->outfd = -1;
802                         break;
803                 case 'c':
804                         coverage_report = optarg;
805                         break;
806                 case 'S':
807                         statistics = TRUE;
808                         break;
809                 default:
810                         usage(NULL);
811                 }
812         }
813         if (argc > optind)
814                 usage(NULL);
815         if (g_slist_length(pdlist) == 0)
816                 usage(NULL);
817         if (!opt_infile)
818                 usage(NULL);
819         if (!op->pd || op->type == -1)
820                 usage(NULL);
821
822         sr_log_callback_set(sr_log, NULL);
823         if (sr_init(&ctx) != SR_OK)
824                 return 1;
825
826         srd_log_callback_set(srd_log, NULL);
827         if (srd_init(DECODERS_DIR) != SRD_OK)
828                 return 1;
829
830         if (coverage_report) {
831                 if (!(coverage = start_coverage(pdlist))) {
832                         DBG("Failed to start coverage.");
833                         if (PyErr_Occurred()) {
834                                 PyErr_PrintEx(0);
835                                 PyErr_Clear();
836                         }
837                 }
838         }
839
840         ret = 0;
841         if (!run_testcase(opt_infile, pdlist, op))
842                 ret = 1;
843
844         if (coverage) {
845                 DBG("Stopping coverage.");
846
847                 if (!(PyObject_CallMethod(coverage, "stop", NULL)))
848                         ERR("Failed to stop coverage.");
849                 else if (!(report_coverage(coverage, pdlist)))
850                         ERR("Failed to make coverage report.");
851                 else
852                         DBG("Coverage report in %s", coverage_report);
853
854                 if (PyErr_Occurred()) {
855                         PyErr_PrintEx(0);
856                         PyErr_Clear();
857                 }
858                 Py_DecRef(coverage);
859         }
860
861         srd_exit();
862         sr_exit(ctx);
863
864         return ret;
865 }