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