2 * This file is part of the libsigrokdecode project.
4 * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
21 #include "../libsigrokdecode.h"
22 #include <libsigrok/libsigrok.h>
28 #include <sys/types.h>
33 #include <sys/resource.h>
42 int statistics = FALSE;
43 char *coverage_report;
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);
84 static void logmsg(char *prefix, FILE *out, const char *format, va_list args)
87 fprintf(out, "%s", prefix);
88 vfprintf(out, format, args);
92 static void DBG(const char *format, ...)
98 va_start(args, format);
99 logmsg("DBG: runtc: ", stdout, format, args);
103 static void ERR(const char *format, ...)
107 va_start(args, format);
108 logmsg("Error: ", stderr, format, args);
112 static int sr_log(void *cb_data, int loglevel, const char *format, va_list args)
116 if (loglevel == SR_LOG_ERR || loglevel == SR_LOG_WARN)
117 logmsg("Error: sr: ", stderr, format, args);
119 logmsg("DBG: sr: ", stdout, format, args);
124 static int srd_log(void *cb_data, int loglevel, const char *format, va_list args)
128 if (loglevel == SRD_LOG_ERR || loglevel == SRD_LOG_WARN)
129 logmsg("Error: srd: ", stderr, format, args);
131 logmsg("DBG: srd: ", stdout, format, args);
136 static void usage(char *msg)
139 fprintf(stderr, "%s\n", msg);
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");
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)
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);
170 static void srd_cb_py(struct srd_proto_data *pdata, void *cb_data)
173 PyObject *pydata, *pyrepr;
177 DBG("Python output from %s", pdata->pdo->di->inst_id);
179 pydata = pdata->data;
180 DBG("ptr %p", pydata);
182 if (strcmp(pdata->pdo->di->inst_id, op->pd))
183 /* This is not the PD selected for output. */
186 if (!(pyrepr = PyObject_Repr(pydata))) {
187 ERR("Invalid Python object.");
190 s = py_str_as_str(pyrepr);
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);
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);
206 static void srd_cb_bin(struct srd_proto_data *pdata, void *cb_data)
208 struct srd_proto_data_binary *pdb;
213 DBG("Binary output from %s", pdata->pdo->di->inst_id);
217 if (strcmp(pdata->pdo->di->inst_id, op->pd))
218 /* This is not the PD selected for output. */
221 if (op->class_idx != -1 && op->class_idx != pdb->bin_class)
223 * This output takes a specific binary class,
224 * but not the one that just came in.
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]);
235 g_string_append(out, "\n");
236 if (write(op->outfd, out->str, out->len) == -1)
237 ERR("SRD_OUTPUT_BINARY callback write failure!");
241 static void srd_cb_ann(struct srd_proto_data *pdata, void *cb_data)
243 struct srd_decoder *dec;
244 struct srd_proto_data_annotation *pda;
250 DBG("Annotation output from %s", pdata->pdo->di->inst_id);
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. */
258 if (op->class_idx != -1 && op->class_idx != pda->ann_format)
260 * This output takes a specific annotation class,
261 * but not the one that just came in.
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);
279 static void sr_cb(const struct sr_dev_inst *sdi,
280 const struct sr_datafeed_packet *packet, void *cb_data)
282 const struct sr_datafeed_logic *logic;
283 struct srd_session *sess;
287 static int samplecnt = 0;
291 switch (packet->type) {
293 DBG("Received SR_DF_HEADER");
294 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
296 ERR("Getting samplerate failed");
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");
306 if (srd_session_start(sess) != SRD_OK) {
307 ERR("Session start failed");
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;
320 DBG("Received SR_DF_END");
326 static int run_testcase(char *infile, GSList *pdlist, struct output *op)
328 struct srd_session *sess;
329 struct srd_decoder *dec;
330 struct srd_decoder_inst *di, *prev_di;
331 srd_pd_output_callback cb;
333 struct channel *channel;
334 struct option *option;
336 GHashTable *channels, *opts;
340 char **decoder_class;
343 if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
344 ERR("Unable to open %s for writing: %s", op->outfile,
350 if (sr_session_load(infile) != SR_OK)
353 if (srd_session_new(&sess) != SRD_OK)
355 sr_session_datafeed_callback_add(sr_cb, sess);
360 case SRD_OUTPUT_BINARY:
363 case SRD_OUTPUT_PYTHON:
369 srd_pd_output_callback_add(sess, op->type, cb, op);
373 for (pdl = pdlist; pdl; pdl = pdl->next) {
375 if (srd_decoder_load(pd->name) != SRD_OK)
378 /* Instantiate decoder and pass in options. */
379 opts = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
380 (GDestroyNotify)g_variant_unref);
381 for (l = pd->options; l; l = l->next) {
383 g_hash_table_insert(opts, option->key, option->value);
385 if (!(di = srd_inst_new(sess, pd->name, opts)))
387 g_hash_table_destroy(opts);
391 channels = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
392 (GDestroyNotify)g_variant_unref);
394 for (l = pd->channels; l; l = l->next) {
396 if (channel->channel > max_channel)
397 max_channel = channel->channel;
398 gvar = g_variant_new_int32(channel->channel);
399 g_variant_ref_sink(gvar);
400 g_hash_table_insert(channels, channel->name, gvar);
402 if (srd_inst_channel_set_all(di, channels,
403 (max_channel + 8) / 8) != SRD_OK)
405 g_hash_table_destroy(channels);
408 /* If this is not the first decoder in the list, stack it
409 * on top of the previous one. */
411 if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
412 ERR("Failed to stack decoder instances.");
419 /* Resolve top decoder's class index, so we can match. */
420 dec = srd_decoder_get_by_id(pd->name);
422 if (op->type == SRD_OUTPUT_ANN)
423 l = dec->annotations;
424 else if (op->type == SRD_OUTPUT_BINARY)
427 /* Only annotations and binary can have a class. */
431 decoder_class = l->data;
432 if (!strcmp(decoder_class[0], op->class)) {
439 if (op->class_idx == -1) {
440 ERR("Output class '%s' not found in decoder %s.",
441 op->class, pd->name);
444 DBG("Class %s index is %d", op->class, op->class_idx);
451 srd_session_destroy(sess);
459 static PyObject *start_coverage(GSList *pdlist)
461 PyObject *py_mod, *py_pdlist, *py_pd, *py_func, *py_args, *py_kwargs, *py_cov;
465 DBG("Starting coverage.");
467 if (!(py_mod = PyImport_ImportModule("coverage")))
470 if (!(py_pdlist = PyList_New(0)))
472 for (l = pdlist; l; l = l->next) {
474 py_pd = PyUnicode_FromFormat("*/%s/*.py", pd->name);
475 if (PyList_Append(py_pdlist, py_pd) < 0)
479 if (!(py_func = PyObject_GetAttrString(py_mod, "coverage")))
481 if (!(py_args = PyTuple_New(0)))
483 if (!(py_kwargs = Py_BuildValue("{sO}", "include", py_pdlist)))
485 if (!(py_cov = PyObject_Call(py_func, py_args, py_kwargs)))
487 if (!(PyObject_CallMethod(py_cov, "start", NULL)))
489 Py_DecRef(py_pdlist);
491 Py_DecRef(py_kwargs);
497 struct cvg *get_mod_cov(PyObject *py_cov, char *module_name)
499 PyObject *py_mod, *py_pathlist, *py_path, *py_func, *py_pd;
500 PyObject *py_result, *py_missed, *py_item;
504 int num_lines, num_missed, linenum, i, j;
505 char *path, *linespec;
507 if (!(py_mod = PyImport_ImportModule(module_name)))
511 py_pathlist = PyObject_GetAttrString(py_mod, "__path__");
512 for (i = 0; i < PyList_Size(py_pathlist); i++) {
513 py_path = PyList_GetItem(py_pathlist, i);
514 PyUnicode_FSConverter(PyList_GetItem(py_pathlist, i), &py_path);
515 path = PyBytes_AS_STRING(py_path);
516 if (!(d = opendir(path))) {
517 ERR("Invalid module path '%s'", path);
520 while ((de = readdir(d))) {
521 if (strncmp(de->d_name + strlen(de->d_name) - 3, ".py", 3))
524 if (!(py_func = PyObject_GetAttrString(py_cov, "analysis2")))
526 if (!(py_pd = PyUnicode_FromFormat("%s/%s", path, de->d_name)))
528 if (!(py_result = PyObject_CallFunction(py_func, "O", py_pd)))
535 if (PyTuple_Size(py_result) != 5) {
536 ERR("Invalid result from coverage of '%s/%s'", path, de->d_name);
539 num_lines = PyList_Size(PyTuple_GetItem(py_result, 1));
540 py_missed = PyTuple_GetItem(py_result, 3);
541 num_missed = PyList_Size(py_missed);
542 cvg_mod->num_lines += num_lines;
543 cvg_mod->num_missed += num_missed;
544 for (j = 0; j < num_missed; j++) {
545 py_item = PyList_GetItem(py_missed, j);
546 linenum = PyLong_AsLong(py_item);
547 linespec = g_strdup_printf("%s/%s:%d", module_name,
548 de->d_name, linenum);
549 cvg_mod->missed_lines = g_slist_append(cvg_mod->missed_lines, linespec);
551 DBG("Coverage for %s/%s: %d lines, %d missed.",
552 module_name, de->d_name, num_lines, num_missed);
553 Py_DecRef(py_result);
556 if (cvg_mod->num_lines)
557 cvg_mod->coverage = 100 - ((float)cvg_mod->num_missed / (float)cvg_mod->num_lines * 100);
565 struct cvg *cvg_new(void)
569 cvg = calloc(1, sizeof(struct cvg));
574 gboolean find_missed_line(struct cvg *cvg, char *linespec)
578 for (l = cvg->missed_lines; l; l = l->next)
579 if (!strcmp(l->data, linespec))
585 void cvg_add(struct cvg *dst, struct cvg *src)
591 dst->num_lines += src->num_lines;
592 dst->num_missed += src->num_missed;
593 for (l = src->missed_lines; l; l = l->next) {
595 if (!find_missed_line(dst, linespec))
596 dst->missed_lines = g_slist_append(dst->missed_lines, linespec);
601 static int report_coverage(PyObject *py_cov, GSList *pdlist)
603 PyObject *py_func, *py_mod, *py_args, *py_kwargs, *py_outfile, *py_pct;
606 struct cvg *cvg_mod, *cvg_all;
607 float total_coverage;
608 int lines, missed, cnt;
610 DBG("Making coverage report.");
612 /* Get coverage for each module in the stack. */
615 for (cnt = 0, l = pdlist; l; l = l->next, cnt++) {
617 if (!(cvg_mod = get_mod_cov(py_cov, pd->name)))
619 printf("coverage: scope=%s coverage=%.0f%% lines=%d missed=%d "
620 "missed_lines=", pd->name, cvg_mod->coverage,
621 cvg_mod->num_lines, cvg_mod->num_missed);
622 for (ml = cvg_mod->missed_lines; ml; ml = ml->next) {
623 if (ml != cvg_mod->missed_lines)
625 printf("%s", (char *)ml->data);
628 lines += cvg_mod->num_lines;
629 missed += cvg_mod->num_missed;
630 cvg_add(cvg_all, cvg_mod);
631 DBG("Coverage for module %s: %d lines, %d missed", pd->name,
632 cvg_mod->num_lines, cvg_mod->num_missed);
636 total_coverage = 100 - ((float)missed / (float)lines * 100);
638 /* Machine-readable stats on stdout. */
639 printf("coverage: scope=all coverage=%.0f%% lines=%d missed=%d\n",
640 total_coverage, cvg_all->num_lines, cvg_all->num_missed);
643 /* Write text report to file. */
644 /* io.open(coverage_report, "w") */
645 if (!(py_mod = PyImport_ImportModule("io")))
647 if (!(py_func = PyObject_GetAttrString(py_mod, "open")))
649 if (!(py_args = PyTuple_New(0)))
651 if (!(py_kwargs = Py_BuildValue("{ssss}", "file", coverage_report,
654 if (!(py_outfile = PyObject_Call(py_func, py_args, py_kwargs)))
656 Py_DecRef(py_kwargs);
659 /* py_cov.report(file=py_outfile) */
660 if (!(py_func = PyObject_GetAttrString(py_cov, "report")))
662 if (!(py_kwargs = Py_BuildValue("{sO}", "file", py_outfile)))
664 if (!(py_pct = PyObject_Call(py_func, py_args, py_kwargs)))
667 Py_DecRef(py_kwargs);
670 /* py_outfile.close() */
671 if (!(py_func = PyObject_GetAttrString(py_outfile, "close")))
673 if (!PyObject_Call(py_func, py_args, NULL))
675 Py_DecRef(py_outfile);
683 int main(int argc, char **argv)
685 struct sr_context *ctx;
689 struct channel *channel;
690 struct option *option;
693 char *opt_infile, **kv, **opstr;
695 op = malloc(sizeof(struct output));
706 while ((c = getopt(argc, argv, "dP:p:o:i:O:f:c:S")) != -1) {
712 pd = g_malloc(sizeof(struct pd));
713 pd->name = g_strdup(optarg);
714 pd->channels = pd->options = NULL;
715 pdlist = g_slist_append(pdlist, pd);
719 if (g_slist_length(pdlist) == 0) {
720 /* No previous -P. */
721 ERR("Syntax error at '%s'", optarg);
724 kv = g_strsplit(optarg, "=", 0);
725 if (!kv[0] || (!kv[1] || kv[2])) {
727 ERR("Syntax error at '%s'", optarg);
732 channel = malloc(sizeof(struct channel));
733 channel->name = g_strdup(kv[0]);
734 channel->channel = strtoul(kv[1], 0, 10);
735 /* Apply to last PD. */
736 pd->channels = g_slist_append(pd->channels, channel);
738 option = malloc(sizeof(struct option));
739 option->key = g_strdup(kv[0]);
740 option->value = g_variant_new_string(kv[1]);
741 g_variant_ref_sink(option->value);
742 /* Apply to last PD. */
743 pd->options = g_slist_append(pd->options, option);
750 opstr = g_strsplit(optarg, ":", 0);
751 if (!opstr[0] || !opstr[1]) {
752 /* Need at least abc:def. */
753 ERR("Syntax error at '%s'", optarg);
757 op->pd = g_strdup(opstr[0]);
758 if (!strcmp(opstr[1], "annotation"))
759 op->type = SRD_OUTPUT_ANN;
760 else if (!strcmp(opstr[1], "binary"))
761 op->type = SRD_OUTPUT_BINARY;
762 else if (!strcmp(opstr[1], "python"))
763 op->type = SRD_OUTPUT_PYTHON;
764 else if (!strcmp(opstr[1], "exception"))
765 /* Doesn't matter, we just need it to bomb out. */
766 op->type = SRD_OUTPUT_PYTHON;
768 ERR("Unknown output type '%s'", opstr[1]);
773 op->class = g_strdup(opstr[2]);
777 op->outfile = g_strdup(optarg);
781 coverage_report = optarg;
792 if (g_slist_length(pdlist) == 0)
796 if (!op->pd || op->type == -1)
799 sr_log_callback_set(sr_log, NULL);
800 if (sr_init(&ctx) != SR_OK)
803 srd_log_callback_set(srd_log, NULL);
804 if (srd_init(DECODERS_DIR) != SRD_OK)
807 if (coverage_report) {
808 if (!(coverage = start_coverage(pdlist))) {
809 DBG("Failed to start coverage.");
810 if (PyErr_Occurred()) {
818 if (!run_testcase(opt_infile, pdlist, op))
822 DBG("Stopping coverage.");
824 if (!(PyObject_CallMethod(coverage, "stop", NULL)))
825 ERR("Failed to stop coverage.");
826 else if (!(report_coverage(coverage, pdlist)))
827 ERR("Failed to make coverage report.");
829 DBG("Coverage report in %s", coverage_report);
831 if (PyErr_Occurred()) {