2 * This file is part of the sigrok-test 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/libsigrokdecode.h>
22 #include <libsigrok/libsigrok.h>
28 #include <sys/types.h>
33 #include <sys/resource.h>
41 int statistics = FALSE;
42 char *coverage_report;
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);
81 static void logmsg(char *prefix, FILE *out, const char *format, va_list args)
84 fprintf(out, "%s", prefix);
85 vfprintf(out, format, args);
89 static void DBG(const char *format, ...)
95 va_start(args, format);
96 logmsg("DBG: runtc: ", stdout, format, args);
100 static void ERR(const char *format, ...)
104 va_start(args, format);
105 logmsg("Error: ", stderr, format, args);
109 static int sr_log(void *cb_data, int loglevel, const char *format, va_list args)
113 if (loglevel == SR_LOG_ERR || loglevel == SR_LOG_WARN)
114 logmsg("Error: sr: ", stderr, format, args);
116 logmsg("DBG: sr: ", stdout, format, args);
121 static int srd_log(void *cb_data, int loglevel, const char *format, va_list args)
125 if (loglevel == SRD_LOG_ERR || loglevel == SRD_LOG_WARN)
126 logmsg("Error: srd: ", stderr, format, args);
128 logmsg("DBG: srd: ", stdout, format, args);
133 static void usage(char *msg)
136 fprintf(stderr, "%s\n", msg);
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");
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)
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);
167 static void srd_cb_py(struct srd_proto_data *pdata, void *cb_data)
170 PyObject *pydata, *pyrepr;
174 DBG("Python output from %s", pdata->pdo->di->inst_id);
176 pydata = pdata->data;
177 DBG("ptr %p", pydata);
179 if (strcmp(pdata->pdo->di->inst_id, op->pd))
180 /* This is not the PD selected for output. */
183 if (!(pyrepr = PyObject_Repr(pydata))) {
184 ERR("Invalid Python object.");
187 s = py_str_as_str(pyrepr);
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);
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);
203 static void srd_cb_bin(struct srd_proto_data *pdata, void *cb_data)
205 struct srd_proto_data_binary *pdb;
210 DBG("Binary output from %s", pdata->pdo->di->inst_id);
214 if (strcmp(pdata->pdo->di->inst_id, op->pd))
215 /* This is not the PD selected for output. */
218 if (op->class_idx != -1 && op->class_idx != pdb->bin_class)
220 * This output takes a specific binary class,
221 * but not the one that just came in.
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]);
232 g_string_append(out, "\n");
233 if (write(op->outfd, out->str, out->len) == -1)
234 ERR("SRD_OUTPUT_BINARY callback write failure!");
238 static void srd_cb_ann(struct srd_proto_data *pdata, void *cb_data)
240 struct srd_decoder *dec;
241 struct srd_proto_data_annotation *pda;
247 DBG("Annotation output from %s", pdata->pdo->di->inst_id);
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. */
255 if (op->class_idx != -1 && op->class_idx != pda->ann_format)
257 * This output takes a specific annotation class,
258 * but not the one that just came in.
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);
276 static void sr_cb(const struct sr_dev_inst *sdi,
277 const struct sr_datafeed_packet *packet, void *cb_data)
279 const struct sr_datafeed_logic *logic;
280 struct srd_session *sess;
284 static int samplecnt = 0;
288 switch (packet->type) {
290 DBG("Received SR_DF_HEADER");
291 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
293 ERR("Getting samplerate failed");
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");
303 if (srd_session_start(sess) != SRD_OK) {
304 ERR("Session start failed");
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;
317 DBG("Received SR_DF_END");
323 static int run_testcase(char *infile, GSList *pdlist, struct output *op)
325 struct srd_session *sess;
326 struct srd_decoder *dec;
327 struct srd_decoder_inst *di, *prev_di;
328 srd_pd_output_callback cb;
330 struct channel *channel;
331 struct option *option;
333 GHashTable *channels, *opts;
337 char **decoder_class;
338 struct sr_session *sr_sess;
341 if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
342 ERR("Unable to open %s for writing: %s", op->outfile,
348 if (sr_session_load(infile, &sr_sess) != SR_OK)
351 if (srd_session_new(&sess) != SRD_OK)
353 sr_session_datafeed_callback_add(sr_sess, sr_cb, sess);
358 case SRD_OUTPUT_BINARY:
361 case SRD_OUTPUT_PYTHON:
367 srd_pd_output_callback_add(sess, op->type, cb, op);
371 for (pdl = pdlist; pdl; pdl = pdl->next) {
373 if (srd_decoder_load(pd->name) != SRD_OK)
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) {
381 g_hash_table_insert(opts, option->key, option->value);
383 if (!(di = srd_inst_new(sess, pd->name, opts)))
385 g_hash_table_destroy(opts);
389 channels = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
390 (GDestroyNotify)g_variant_unref);
392 for (l = pd->channels; l; l = l->next) {
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);
400 if (srd_inst_channel_set_all(di, channels,
401 (max_channel + 8) / 8) != SRD_OK)
403 g_hash_table_destroy(channels);
406 /* If this is not the first decoder in the list, stack it
407 * on top of the previous one. */
409 if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
410 ERR("Failed to stack decoder instances.");
417 /* Resolve top decoder's class index, so we can match. */
418 dec = srd_decoder_get_by_id(pd->name);
420 if (op->type == SRD_OUTPUT_ANN)
421 l = dec->annotations;
422 else if (op->type == SRD_OUTPUT_BINARY)
425 /* Only annotations and binary can have a class. */
429 decoder_class = l->data;
430 if (!strcmp(decoder_class[0], op->class)) {
437 if (op->class_idx == -1) {
438 ERR("Output class '%s' not found in decoder %s.",
439 op->class, pd->name);
442 DBG("Class %s index is %d", op->class, op->class_idx);
445 sr_session_start(sr_sess);
446 sr_session_run(sr_sess);
447 sr_session_stop(sr_sess);
449 srd_session_destroy(sess);
457 static PyObject *start_coverage(GSList *pdlist)
459 PyObject *py_mod, *py_pdlist, *py_pd, *py_func, *py_args, *py_kwargs, *py_cov;
463 DBG("Starting coverage.");
465 if (!(py_mod = PyImport_ImportModule("coverage")))
468 if (!(py_pdlist = PyList_New(0)))
470 for (l = pdlist; l; l = l->next) {
472 py_pd = PyUnicode_FromFormat("*/%s/*.py", pd->name);
473 if (PyList_Append(py_pdlist, py_pd) < 0)
477 if (!(py_func = PyObject_GetAttrString(py_mod, "coverage")))
479 if (!(py_args = PyTuple_New(0)))
481 if (!(py_kwargs = Py_BuildValue("{sO}", "include", py_pdlist)))
483 if (!(py_cov = PyObject_Call(py_func, py_args, py_kwargs)))
485 if (!(PyObject_CallMethod(py_cov, "start", NULL)))
487 Py_DecRef(py_pdlist);
489 Py_DecRef(py_kwargs);
495 struct cvg *get_mod_cov(PyObject *py_cov, char *module_name)
497 PyObject *py_mod, *py_pathlist, *py_path, *py_func, *py_pd;
498 PyObject *py_result, *py_missed, *py_item;
502 int num_lines, num_missed, linenum, i, j;
503 char *path, *linespec;
505 if (!(py_mod = PyImport_ImportModule(module_name)))
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);
518 while ((de = readdir(d))) {
519 if (strncmp(de->d_name + strlen(de->d_name) - 3, ".py", 3))
522 if (!(py_func = PyObject_GetAttrString(py_cov, "analysis2")))
524 if (!(py_pd = PyUnicode_FromFormat("%s/%s", path, de->d_name)))
526 if (!(py_result = PyObject_CallFunction(py_func, "O", py_pd)))
533 if (PyTuple_Size(py_result) != 5) {
534 ERR("Invalid result from coverage of '%s/%s'", path, de->d_name);
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);
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);
554 if (cvg_mod->num_lines)
555 cvg_mod->coverage = 100 - ((float)cvg_mod->num_missed / (float)cvg_mod->num_lines * 100);
563 struct cvg *cvg_new(void)
567 cvg = calloc(1, sizeof(struct cvg));
572 gboolean find_missed_line(struct cvg *cvg, char *linespec)
576 for (l = cvg->missed_lines; l; l = l->next)
577 if (!strcmp(l->data, linespec))
583 void cvg_add(struct cvg *dst, struct cvg *src)
588 dst->num_lines += src->num_lines;
589 dst->num_missed += src->num_missed;
590 for (l = src->missed_lines; l; l = l->next) {
592 if (!find_missed_line(dst, linespec))
593 dst->missed_lines = g_slist_append(dst->missed_lines, linespec);
598 static int report_coverage(PyObject *py_cov, GSList *pdlist)
600 PyObject *py_func, *py_mod, *py_args, *py_kwargs, *py_outfile, *py_pct;
603 struct cvg *cvg_mod, *cvg_all;
604 float total_coverage;
605 int lines, missed, cnt;
607 DBG("Making coverage report.");
609 /* Get coverage for each module in the stack. */
612 for (cnt = 0, l = pdlist; l; l = l->next, cnt++) {
614 if (!(cvg_mod = get_mod_cov(py_cov, pd->name)))
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)
622 printf("%s", (char *)ml->data);
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);
633 total_coverage = 100 - ((float)missed / (float)lines * 100);
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);
639 /* Write text report to file. */
640 /* io.open(coverage_report, "w") */
641 if (!(py_mod = PyImport_ImportModule("io")))
643 if (!(py_func = PyObject_GetAttrString(py_mod, "open")))
645 if (!(py_args = PyTuple_New(0)))
647 if (!(py_kwargs = Py_BuildValue("{ssss}", "file", coverage_report,
650 if (!(py_outfile = PyObject_Call(py_func, py_args, py_kwargs)))
652 Py_DecRef(py_kwargs);
655 /* py_cov.report(file=py_outfile) */
656 if (!(py_func = PyObject_GetAttrString(py_cov, "report")))
658 if (!(py_kwargs = Py_BuildValue("{sO}", "file", py_outfile)))
660 if (!(py_pct = PyObject_Call(py_func, py_args, py_kwargs)))
663 Py_DecRef(py_kwargs);
666 /* py_outfile.close() */
667 if (!(py_func = PyObject_GetAttrString(py_outfile, "close")))
669 if (!PyObject_Call(py_func, py_args, NULL))
671 Py_DecRef(py_outfile);
679 int main(int argc, char **argv)
681 struct sr_context *ctx;
685 struct channel *channel;
686 struct option *option;
689 char *opt_infile, **kv, **opstr;
691 op = malloc(sizeof(struct output));
702 while ((c = getopt(argc, argv, "dP:p:o:i:O:f:c:S")) != -1) {
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);
715 if (g_slist_length(pdlist) == 0) {
716 /* No previous -P. */
717 ERR("Syntax error at '%s'", optarg);
720 kv = g_strsplit(optarg, "=", 0);
721 if (!kv[0] || (!kv[1] || kv[2])) {
723 ERR("Syntax error at '%s'", optarg);
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);
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);
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);
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;
764 ERR("Unknown output type '%s'", opstr[1]);
769 op->class = g_strdup(opstr[2]);
773 op->outfile = g_strdup(optarg);
777 coverage_report = optarg;
788 if (g_slist_length(pdlist) == 0)
792 if (!op->pd || op->type == -1)
795 sr_log_callback_set(sr_log, NULL);
796 if (sr_init(&ctx) != SR_OK)
799 srd_log_callback_set(srd_log, NULL);
800 if (srd_init(DECODERS_DIR) != SRD_OK)
803 if (coverage_report) {
804 if (!(coverage = start_coverage(pdlist))) {
805 DBG("Failed to start coverage.");
806 if (PyErr_Occurred()) {
814 if (!run_testcase(opt_infile, pdlist, op))
818 DBG("Stopping coverage.");
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.");
825 DBG("Coverage report in %s", coverage_report);
827 if (PyErr_Occurred()) {