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;
77 struct cvg *get_mod_cov(PyObject *py_cov, char *module_name);
78 void cvg_add(struct cvg *dst, struct cvg *src);
79 struct cvg *cvg_new(void);
80 gboolean find_missed_line(struct cvg *cvg, char *linespec);
82 static void logmsg(char *prefix, FILE *out, const char *format, va_list args)
85 fprintf(out, "%s", prefix);
86 vfprintf(out, format, args);
90 static void DBG(const char *format, ...)
96 va_start(args, format);
97 logmsg("DBG: runtc: ", stdout, format, args);
101 static void ERR(const char *format, ...)
105 va_start(args, format);
106 logmsg("Error: ", stderr, format, args);
110 static int sr_log(void *cb_data, int loglevel, const char *format, va_list args)
114 if (loglevel == SR_LOG_ERR || loglevel == SR_LOG_WARN)
115 logmsg("Error: sr: ", stderr, format, args);
117 logmsg("DBG: sr: ", stdout, format, args);
122 static int srd_log(void *cb_data, int loglevel, const char *format, va_list args)
126 if (loglevel == SRD_LOG_ERR || loglevel == SRD_LOG_WARN)
127 logmsg("Error: srd: ", stderr, format, args);
129 logmsg("DBG: srd: ", stdout, format, args);
134 static void usage(char *msg)
137 fprintf(stderr, "%s\n", msg);
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");
152 /* This is a neutered version of libsigrokdecode's py_str_as_str(). It
153 * does no error checking, but then the only strings it processes are
154 * generated by Python's repr(), so are known good. */
155 static char *py_str_as_str(const PyObject *py_str)
160 py_encstr = PyUnicode_AsEncodedString((PyObject *)py_str, "utf-8", NULL);
161 str = PyBytes_AS_STRING(py_encstr);
162 outstr = g_strdup(str);
163 Py_DecRef(py_encstr);
168 static void srd_cb_py(struct srd_proto_data *pdata, void *cb_data)
171 PyObject *pydata, *pyrepr;
175 DBG("Python output from %s", pdata->pdo->di->inst_id);
177 pydata = pdata->data;
178 DBG("ptr %p", pydata);
180 if (strcmp(pdata->pdo->di->inst_id, op->pd))
181 /* This is not the PD selected for output. */
184 if (!(pyrepr = PyObject_Repr(pydata))) {
185 ERR("Invalid Python object.");
188 s = py_str_as_str(pyrepr);
191 /* Output format for testing is '<ss>-<es> <inst-id>: <repr>\n'. */
192 out = g_string_sized_new(128);
193 g_string_printf(out, "%" PRIu64 "-%" PRIu64 " %s: %s\n",
194 pdata->start_sample, pdata->end_sample,
195 pdata->pdo->di->inst_id, s);
197 if (write(op->outfd, out->str, out->len) == -1)
198 ERR("SRD_OUTPUT_PYTHON callback write failure!");
199 DBG("wrote '%s'", out->str);
200 g_string_free(out, TRUE);
204 static void srd_cb_bin(struct srd_proto_data *pdata, void *cb_data)
206 struct srd_proto_data_binary *pdb;
211 DBG("Binary output from %s", pdata->pdo->di->inst_id);
215 if (strcmp(pdata->pdo->di->inst_id, op->pd))
216 /* This is not the PD selected for output. */
219 if (op->class_idx != -1 && op->class_idx != pdb->bin_class)
221 * This output takes a specific binary class,
222 * but not the one that just came in.
226 out = g_string_sized_new(128);
227 g_string_printf(out, "%" PRIu64 "-%" PRIu64 " %s:",
228 pdata->start_sample, pdata->end_sample,
229 pdata->pdo->di->inst_id);
230 for (i = 0; i < pdb->size; i++) {
231 g_string_append_printf(out, " %.2x", pdb->data[i]);
233 g_string_append(out, "\n");
234 if (write(op->outfd, out->str, out->len) == -1)
235 ERR("SRD_OUTPUT_BINARY callback write failure!");
239 static void srd_cb_ann(struct srd_proto_data *pdata, void *cb_data)
241 struct srd_decoder *dec;
242 struct srd_proto_data_annotation *pda;
248 DBG("Annotation output from %s", pdata->pdo->di->inst_id);
251 dec = pdata->pdo->di->decoder;
252 if (strcmp(pdata->pdo->di->inst_id, op->pd))
253 /* This is not the PD selected for output. */
256 if (op->class_idx != -1 && op->class_idx != pda->ann_format)
258 * This output takes a specific annotation class,
259 * but not the one that just came in.
263 dec_ann = g_slist_nth_data(dec->annotations, pda->ann_format);
264 line = g_string_sized_new(256);
265 g_string_printf(line, "%" PRIu64 "-%" PRIu64 " %s: %s:",
266 pdata->start_sample, pdata->end_sample,
267 pdata->pdo->di->inst_id, dec_ann[0]);
268 for (i = 0; pda->ann_text[i]; i++)
269 g_string_append_printf(line, " \"%s\"", pda->ann_text[i]);
270 g_string_append(line, "\n");
271 if (write(op->outfd, line->str, line->len) == -1)
272 ERR("SRD_OUTPUT_ANN callback write failure!");
273 g_string_free(line, TRUE);
277 static void sr_cb(const struct sr_dev_inst *sdi,
278 const struct sr_datafeed_packet *packet, void *cb_data)
280 const struct sr_datafeed_logic *logic;
281 struct srd_session *sess;
285 static int samplecnt = 0;
289 switch (packet->type) {
291 DBG("Received SR_DF_HEADER");
292 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
294 ERR("Getting samplerate failed");
297 samplerate = g_variant_get_uint64(gvar);
298 g_variant_unref(gvar);
299 if (srd_session_metadata_set(sess, SRD_CONF_SAMPLERATE,
300 g_variant_new_uint64(samplerate)) != SRD_OK) {
301 ERR("Setting samplerate failed");
304 if (srd_session_start(sess) != SRD_OK) {
305 ERR("Session start failed");
310 logic = packet->payload;
311 num_samples = logic->length / logic->unitsize;
312 DBG("Received SR_DF_LOGIC: %d samples", num_samples);
313 srd_session_send(sess, samplecnt, samplecnt + num_samples,
314 logic->data, logic->length);
315 samplecnt += logic->length / logic->unitsize;
318 DBG("Received SR_DF_END");
324 static int run_testcase(char *infile, GSList *pdlist, struct output *op)
326 struct srd_session *sess;
327 struct srd_decoder *dec;
328 struct srd_decoder_inst *di, *prev_di;
329 srd_pd_output_callback cb;
331 struct channel *channel;
332 struct option *option;
334 GHashTable *channels, *opts;
338 char **decoder_class;
339 struct sr_session *sr_sess;
342 if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
343 ERR("Unable to open %s for writing: %s", op->outfile,
349 if (sr_session_load(infile, &sr_sess) != SR_OK)
352 if (srd_session_new(&sess) != SRD_OK)
354 sr_session_datafeed_callback_add(sr_sess, sr_cb, sess);
359 case SRD_OUTPUT_BINARY:
362 case SRD_OUTPUT_PYTHON:
368 srd_pd_output_callback_add(sess, op->type, cb, op);
372 for (pdl = pdlist; pdl; pdl = pdl->next) {
374 if (srd_decoder_load(pd->name) != SRD_OK)
377 /* Instantiate decoder and pass in options. */
378 opts = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
379 (GDestroyNotify)g_variant_unref);
380 for (l = pd->options; l; l = l->next) {
382 g_hash_table_insert(opts, option->key, option->value);
384 if (!(di = srd_inst_new(sess, pd->name, opts)))
386 g_hash_table_destroy(opts);
390 channels = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
391 (GDestroyNotify)g_variant_unref);
393 for (l = pd->channels; l; l = l->next) {
395 if (channel->channel > max_channel)
396 max_channel = channel->channel;
397 gvar = g_variant_new_int32(channel->channel);
398 g_variant_ref_sink(gvar);
399 g_hash_table_insert(channels, channel->name, gvar);
401 if (srd_inst_channel_set_all(di, channels,
402 (max_channel + 8) / 8) != SRD_OK)
404 g_hash_table_destroy(channels);
407 /* If this is not the first decoder in the list, stack it
408 * on top of the previous one. */
410 if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
411 ERR("Failed to stack decoder instances.");
418 /* Resolve top decoder's class index, so we can match. */
419 dec = srd_decoder_get_by_id(pd->name);
421 if (op->type == SRD_OUTPUT_ANN)
422 l = dec->annotations;
423 else if (op->type == SRD_OUTPUT_BINARY)
426 /* Only annotations and binary can have a class. */
430 decoder_class = l->data;
431 if (!strcmp(decoder_class[0], op->class)) {
438 if (op->class_idx == -1) {
439 ERR("Output class '%s' not found in decoder %s.",
440 op->class, pd->name);
443 DBG("Class %s index is %d", op->class, op->class_idx);
446 sr_session_start(sr_sess);
447 sr_session_run(sr_sess);
448 sr_session_stop(sr_sess);
450 srd_session_destroy(sess);
458 static PyObject *start_coverage(GSList *pdlist)
460 PyObject *py_mod, *py_pdlist, *py_pd, *py_func, *py_args, *py_kwargs, *py_cov;
464 DBG("Starting coverage.");
466 if (!(py_mod = PyImport_ImportModule("coverage")))
469 if (!(py_pdlist = PyList_New(0)))
471 for (l = pdlist; l; l = l->next) {
473 py_pd = PyUnicode_FromFormat("*/%s/*.py", pd->name);
474 if (PyList_Append(py_pdlist, py_pd) < 0)
478 if (!(py_func = PyObject_GetAttrString(py_mod, "coverage")))
480 if (!(py_args = PyTuple_New(0)))
482 if (!(py_kwargs = Py_BuildValue("{sO}", "include", py_pdlist)))
484 if (!(py_cov = PyObject_Call(py_func, py_args, py_kwargs)))
486 if (!(PyObject_CallMethod(py_cov, "start", NULL)))
488 Py_DecRef(py_pdlist);
490 Py_DecRef(py_kwargs);
496 struct cvg *get_mod_cov(PyObject *py_cov, char *module_name)
498 PyObject *py_mod, *py_pathlist, *py_path, *py_func, *py_pd;
499 PyObject *py_result, *py_missed, *py_item;
503 int num_lines, num_missed, linenum, i, j;
504 char *path, *linespec;
506 if (!(py_mod = PyImport_ImportModule(module_name)))
510 py_pathlist = PyObject_GetAttrString(py_mod, "__path__");
511 for (i = 0; i < PyList_Size(py_pathlist); i++) {
512 py_path = PyList_GetItem(py_pathlist, i);
513 PyUnicode_FSConverter(PyList_GetItem(py_pathlist, i), &py_path);
514 path = PyBytes_AS_STRING(py_path);
515 if (!(d = opendir(path))) {
516 ERR("Invalid module path '%s'", path);
519 while ((de = readdir(d))) {
520 if (strncmp(de->d_name + strlen(de->d_name) - 3, ".py", 3))
523 if (!(py_func = PyObject_GetAttrString(py_cov, "analysis2")))
525 if (!(py_pd = PyUnicode_FromFormat("%s/%s", path, de->d_name)))
527 if (!(py_result = PyObject_CallFunction(py_func, "O", py_pd)))
534 if (PyTuple_Size(py_result) != 5) {
535 ERR("Invalid result from coverage of '%s/%s'", path, de->d_name);
538 num_lines = PyList_Size(PyTuple_GetItem(py_result, 1));
539 py_missed = PyTuple_GetItem(py_result, 3);
540 num_missed = PyList_Size(py_missed);
541 cvg_mod->num_lines += num_lines;
542 cvg_mod->num_missed += num_missed;
543 for (j = 0; j < num_missed; j++) {
544 py_item = PyList_GetItem(py_missed, j);
545 linenum = PyLong_AsLong(py_item);
546 linespec = g_strdup_printf("%s/%s:%d", module_name,
547 de->d_name, linenum);
548 cvg_mod->missed_lines = g_slist_append(cvg_mod->missed_lines, linespec);
550 DBG("Coverage for %s/%s: %d lines, %d missed.",
551 module_name, de->d_name, num_lines, num_missed);
552 Py_DecRef(py_result);
555 if (cvg_mod->num_lines)
556 cvg_mod->coverage = 100 - ((float)cvg_mod->num_missed / (float)cvg_mod->num_lines * 100);
564 struct cvg *cvg_new(void)
568 cvg = calloc(1, sizeof(struct cvg));
573 gboolean find_missed_line(struct cvg *cvg, char *linespec)
577 for (l = cvg->missed_lines; l; l = l->next)
578 if (!strcmp(l->data, linespec))
584 void cvg_add(struct cvg *dst, struct cvg *src)
589 dst->num_lines += src->num_lines;
590 dst->num_missed += src->num_missed;
591 for (l = src->missed_lines; l; l = l->next) {
593 if (!find_missed_line(dst, linespec))
594 dst->missed_lines = g_slist_append(dst->missed_lines, linespec);
599 static int report_coverage(PyObject *py_cov, GSList *pdlist)
601 PyObject *py_func, *py_mod, *py_args, *py_kwargs, *py_outfile, *py_pct;
604 struct cvg *cvg_mod, *cvg_all;
605 float total_coverage;
606 int lines, missed, cnt;
608 DBG("Making coverage report.");
610 /* Get coverage for each module in the stack. */
613 for (cnt = 0, l = pdlist; l; l = l->next, cnt++) {
615 if (!(cvg_mod = get_mod_cov(py_cov, pd->name)))
617 printf("coverage: scope=%s coverage=%.0f%% lines=%d missed=%d "
618 "missed_lines=", pd->name, cvg_mod->coverage,
619 cvg_mod->num_lines, cvg_mod->num_missed);
620 for (ml = cvg_mod->missed_lines; ml; ml = ml->next) {
621 if (ml != cvg_mod->missed_lines)
623 printf("%s", (char *)ml->data);
626 lines += cvg_mod->num_lines;
627 missed += cvg_mod->num_missed;
628 cvg_add(cvg_all, cvg_mod);
629 DBG("Coverage for module %s: %d lines, %d missed", pd->name,
630 cvg_mod->num_lines, cvg_mod->num_missed);
634 total_coverage = 100 - ((float)missed / (float)lines * 100);
636 /* Machine-readable stats on stdout. */
637 printf("coverage: scope=all coverage=%.0f%% lines=%d missed=%d\n",
638 total_coverage, cvg_all->num_lines, cvg_all->num_missed);
640 /* Write text report to file. */
641 /* io.open(coverage_report, "w") */
642 if (!(py_mod = PyImport_ImportModule("io")))
644 if (!(py_func = PyObject_GetAttrString(py_mod, "open")))
646 if (!(py_args = PyTuple_New(0)))
648 if (!(py_kwargs = Py_BuildValue("{ssss}", "file", coverage_report,
651 if (!(py_outfile = PyObject_Call(py_func, py_args, py_kwargs)))
653 Py_DecRef(py_kwargs);
656 /* py_cov.report(file=py_outfile) */
657 if (!(py_func = PyObject_GetAttrString(py_cov, "report")))
659 if (!(py_kwargs = Py_BuildValue("{sO}", "file", py_outfile)))
661 if (!(py_pct = PyObject_Call(py_func, py_args, py_kwargs)))
664 Py_DecRef(py_kwargs);
667 /* py_outfile.close() */
668 if (!(py_func = PyObject_GetAttrString(py_outfile, "close")))
670 if (!PyObject_Call(py_func, py_args, NULL))
672 Py_DecRef(py_outfile);
680 int main(int argc, char **argv)
682 struct sr_context *ctx;
686 struct channel *channel;
687 struct option *option;
690 char *opt_infile, **kv, **opstr;
692 op = malloc(sizeof(struct output));
703 while ((c = getopt(argc, argv, "dP:p:o:i:O:f:c:S")) != -1) {
709 pd = g_malloc(sizeof(struct pd));
710 pd->name = g_strdup(optarg);
711 pd->channels = pd->options = NULL;
712 pdlist = g_slist_append(pdlist, pd);
716 if (g_slist_length(pdlist) == 0) {
717 /* No previous -P. */
718 ERR("Syntax error at '%s'", optarg);
721 kv = g_strsplit(optarg, "=", 0);
722 if (!kv[0] || (!kv[1] || kv[2])) {
724 ERR("Syntax error at '%s'", optarg);
729 channel = malloc(sizeof(struct channel));
730 channel->name = g_strdup(kv[0]);
731 channel->channel = strtoul(kv[1], 0, 10);
732 /* Apply to last PD. */
733 pd->channels = g_slist_append(pd->channels, channel);
735 option = malloc(sizeof(struct option));
736 option->key = g_strdup(kv[0]);
737 option->value = g_variant_new_string(kv[1]);
738 g_variant_ref_sink(option->value);
739 /* Apply to last PD. */
740 pd->options = g_slist_append(pd->options, option);
747 opstr = g_strsplit(optarg, ":", 0);
748 if (!opstr[0] || !opstr[1]) {
749 /* Need at least abc:def. */
750 ERR("Syntax error at '%s'", optarg);
754 op->pd = g_strdup(opstr[0]);
755 if (!strcmp(opstr[1], "annotation"))
756 op->type = SRD_OUTPUT_ANN;
757 else if (!strcmp(opstr[1], "binary"))
758 op->type = SRD_OUTPUT_BINARY;
759 else if (!strcmp(opstr[1], "python"))
760 op->type = SRD_OUTPUT_PYTHON;
761 else if (!strcmp(opstr[1], "exception"))
762 /* Doesn't matter, we just need it to bomb out. */
763 op->type = SRD_OUTPUT_PYTHON;
765 ERR("Unknown output type '%s'", opstr[1]);
770 op->class = g_strdup(opstr[2]);
774 op->outfile = g_strdup(optarg);
778 coverage_report = optarg;
789 if (g_slist_length(pdlist) == 0)
793 if (!op->pd || op->type == -1)
796 sr_log_callback_set(sr_log, NULL);
797 if (sr_init(&ctx) != SR_OK)
800 srd_log_callback_set(srd_log, NULL);
801 if (srd_init(DECODERS_DIR) != SRD_OK)
804 if (coverage_report) {
805 if (!(coverage = start_coverage(pdlist))) {
806 DBG("Failed to start coverage.");
807 if (PyErr_Occurred()) {
815 if (!run_testcase(opt_infile, pdlist, op))
819 DBG("Stopping coverage.");
821 if (!(PyObject_CallMethod(coverage, "stop", NULL)))
822 ERR("Failed to stop coverage.");
823 else if (!(report_coverage(coverage, pdlist)))
824 ERR("Failed to make coverage report.");
826 DBG("Coverage report in %s", coverage_report);
828 if (PyErr_Occurred()) {