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>
40 static int debug = FALSE;
41 static int statistics = FALSE;
42 static char *coverage_report;
43 static struct sr_context *ctx;
78 static struct cvg *get_mod_cov(PyObject *py_cov, const char *module_name);
79 static void cvg_add(struct cvg *dst, const struct cvg *src);
80 static struct cvg *cvg_new(void);
81 static gboolean find_missed_line(struct cvg *cvg, const char *linespec);
83 static void logmsg(const char *prefix, FILE *out, const char *format, va_list args)
86 fprintf(out, "%s", prefix);
87 vfprintf(out, format, args);
91 static void DBG(const char *format, ...)
97 va_start(args, format);
98 logmsg("DBG: runtc: ", stdout, format, args);
102 static void ERR(const char *format, ...)
106 va_start(args, format);
107 logmsg("Error: ", stderr, format, args);
111 static int sr_log(void *cb_data, int loglevel, const char *format, va_list args)
115 if (loglevel == SR_LOG_ERR || loglevel == SR_LOG_WARN)
116 logmsg("Error: sr: ", stderr, format, args);
118 logmsg("DBG: sr: ", stdout, format, args);
123 static int srd_log(void *cb_data, int loglevel, const char *format, va_list args)
127 if (loglevel == SRD_LOG_ERR || loglevel == SRD_LOG_WARN)
128 logmsg("Error: srd: ", stderr, format, args);
130 logmsg("DBG: srd: ", stdout, format, args);
135 static void usage(const char *msg)
138 fprintf(stderr, "%s\n", msg);
140 printf("Usage: runtc [-dPpoiOfcS]\n");
141 printf(" -d (enables debug output)\n");
142 printf(" -P <protocol decoder>\n");
143 printf(" -p <channelname=channelnum> (optional)\n");
144 printf(" -o <channeloption=value> (optional)\n");
145 printf(" -i <input file>\n");
146 printf(" -O <output-pd:output-type[:output-class]>\n");
147 printf(" -f <output file> (optional)\n");
148 printf(" -c <coverage report> (optional)\n");
149 printf(" -S (enables statistics)\n");
155 * This is a neutered version of libsigrokdecode's py_str_as_str(). It
156 * does no error checking, but then the only strings it processes are
157 * generated by Python's repr(), so are known good.
159 static char *py_str_as_str(const PyObject *py_str)
164 py_encstr = PyUnicode_AsEncodedString((PyObject *)py_str, "utf-8", NULL);
165 str = PyBytes_AS_STRING(py_encstr);
166 outstr = g_strdup(str);
167 Py_DecRef(py_encstr);
173 * The following routines are callbacks for libsigrokdecode. They receive
174 * output from protocol decoders, optionally dropping data to only forward
175 * a selected decoder's or class' information. Output is written to either
176 * a specified file or stdout, an external process will compare captured
177 * output against expectations.
179 * Note that runtc(1) output emits the decoder "class" name instead of the
180 * instance name. So that generated output remains compatible with existing
181 * .output files which hold expected output of test cases. Without this
182 * approach, developers had to "anticipate" instance names from test.conf
183 * setups (and knowledge about internal implementation details of the srd
184 * library), and adjust .output files to reflect those names. Or specify
185 * instance names in each and every test.conf description (-o inst_id=ID).
187 * It's assumed that runtc(1) is used to check stacked decoders, but not
188 * multiple stacks in parallel and no stacks with multiple instances of
189 * decoders of the same type. When such configurations become desirable,
190 * runtc(1) needs to emit the instance name, and test configurations and
191 * output expectations need adjustment.
194 static void srd_cb_py(struct srd_proto_data *pdata, void *cb_data)
197 PyObject *pydata, *pyrepr;
201 DBG("Python output from %s", pdata->pdo->di->inst_id);
203 pydata = pdata->data;
204 DBG("ptr %p", pydata);
206 if (strcmp(pdata->pdo->di->inst_id, op->pd_id))
207 /* This is not the PD selected for output. */
210 if (!(pyrepr = PyObject_Repr(pydata))) {
211 ERR("Invalid Python object.");
214 s = py_str_as_str(pyrepr);
217 /* Output format for testing is '<ss>-<es> <decoder-id>: <repr>\n'. */
218 out = g_string_sized_new(128);
219 g_string_printf(out, "%" PRIu64 "-%" PRIu64 " %s: %s\n",
220 pdata->start_sample, pdata->end_sample,
221 pdata->pdo->di->decoder->id, s);
223 if (write(op->outfd, out->str, out->len) == -1)
224 ERR("SRD_OUTPUT_PYTHON callback write failure!");
225 DBG("wrote '%s'", out->str);
226 g_string_free(out, TRUE);
230 static void srd_cb_bin(struct srd_proto_data *pdata, void *cb_data)
232 struct srd_proto_data_binary *pdb;
237 DBG("Binary output from %s", pdata->pdo->di->inst_id);
241 if (strcmp(pdata->pdo->di->inst_id, op->pd_id))
242 /* This is not the PD selected for output. */
245 if (op->class_idx != -1 && op->class_idx != pdb->bin_class)
247 * This output takes a specific binary class,
248 * but not the one that just came in.
252 out = g_string_sized_new(128);
253 g_string_printf(out, "%" PRIu64 "-%" PRIu64 " %s:",
254 pdata->start_sample, pdata->end_sample,
255 pdata->pdo->di->decoder->id);
256 for (i = 0; i < pdb->size; i++) {
257 g_string_append_printf(out, " %.2x", pdb->data[i]);
259 g_string_append(out, "\n");
260 if (write(op->outfd, out->str, out->len) == -1)
261 ERR("SRD_OUTPUT_BINARY callback write failure!");
265 static void srd_cb_ann(struct srd_proto_data *pdata, void *cb_data)
267 struct srd_decoder_inst *di;
268 struct srd_decoder *dec;
269 struct srd_proto_data_annotation *pda;
276 * Only inspect received annotations when they originate from
277 * the selected protocol decoder, and an optionally specified
278 * annotation class matches the received data.
284 DBG("Annotation output from %s", di->inst_id);
285 if (strcmp(di->inst_id, op->pd_id))
286 /* This is not the PD selected for output. */
289 if (op->class_idx != -1 && op->class_idx != pda->ann_class)
291 * This output takes a specific annotation class,
292 * but not the one that just came in.
297 * Print the annotation information in textual representation
298 * to the specified output file. Prefix the annotation strings
299 * with the start and end sample number, the decoder name, and
300 * the annotation name.
302 dec_ann = g_slist_nth_data(dec->annotations, pda->ann_class);
303 line = g_string_sized_new(256);
304 g_string_printf(line, "%" PRIu64 "-%" PRIu64 " %s: %s:",
305 pdata->start_sample, pdata->end_sample,
306 dec->id, dec_ann[0]);
307 for (i = 0; pda->ann_text[i]; i++)
308 g_string_append_printf(line, " \"%s\"", pda->ann_text[i]);
309 g_string_append(line, "\n");
310 if (write(op->outfd, line->str, line->len) == -1)
311 ERR("SRD_OUTPUT_ANN callback write failure!");
312 g_string_free(line, TRUE);
316 static void sr_cb(const struct sr_dev_inst *sdi,
317 const struct sr_datafeed_packet *packet, void *cb_data)
319 static int samplecnt = 0;
320 const struct sr_datafeed_logic *logic;
321 struct srd_session *sess;
325 struct sr_dev_driver *driver;
329 driver = sr_dev_inst_driver_get(sdi);
331 switch (packet->type) {
333 DBG("Received SR_DF_HEADER");
334 if (sr_config_get(driver, sdi, NULL, SR_CONF_SAMPLERATE,
336 ERR("Getting samplerate failed");
339 samplerate = g_variant_get_uint64(gvar);
340 g_variant_unref(gvar);
341 if (srd_session_metadata_set(sess, SRD_CONF_SAMPLERATE,
342 g_variant_new_uint64(samplerate)) != SRD_OK) {
343 ERR("Setting samplerate failed");
346 if (srd_session_start(sess) != SRD_OK) {
347 ERR("Session start failed");
352 logic = packet->payload;
353 num_samples = logic->length / logic->unitsize;
354 DBG("Received SR_DF_LOGIC (%"PRIu64" bytes, unitsize = %d).",
355 logic->length, logic->unitsize);
356 srd_session_send(sess, samplecnt, samplecnt + num_samples,
357 logic->data, logic->length, logic->unitsize);
358 samplecnt += num_samples;
361 DBG("Received SR_DF_END");
367 static int run_testcase(const char *infile, GSList *pdlist, struct output *op)
369 struct srd_session *sess;
370 struct srd_decoder *dec;
371 struct srd_decoder_inst *di, *prev_di;
372 srd_pd_output_callback cb;
374 struct channel *channel;
375 struct option *option;
377 GHashTable *channels, *opts;
378 GSList *pdl, *l, *devices;
381 char **decoder_class;
382 struct sr_session *sr_sess;
387 if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
388 ERR("Unable to open %s for writing: %s", op->outfile,
394 if (sr_session_load(ctx, infile, &sr_sess) != SR_OK)
397 sr_session_dev_list(sr_sess, &devices);
399 if (srd_session_new(&sess) != SRD_OK)
401 sr_session_datafeed_callback_add(sr_sess, sr_cb, sess);
406 case SRD_OUTPUT_BINARY:
409 case SRD_OUTPUT_PYTHON:
415 srd_pd_output_callback_add(sess, op->type, cb, op);
419 for (pdl = pdlist; pdl; pdl = pdl->next) {
421 if (srd_decoder_load(pd->name) != SRD_OK)
424 /* Instantiate decoder and pass in options. */
425 opts = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
426 (GDestroyNotify)g_variant_unref);
427 for (l = pd->options; l; l = l->next) {
431 s = g_variant_get_string(option->value, NULL);
432 for (i = 0; i < (int)strlen(s); i++) {
438 /* Integer option value */
439 g_hash_table_insert(opts, option->key,
440 g_variant_new_int64(strtoull(s, NULL, 10)));
442 /* String option value */
443 g_hash_table_insert(opts, option->key, option->value);
446 if (!(di = srd_inst_new(sess, pd->name, opts)))
448 g_hash_table_destroy(opts);
451 * Get (a reference to) the decoder instance's ID if we
452 * are about to receive PD output from it. We need to
453 * filter output that carries the decoder instance's name.
455 if (strcmp(pd->name, op->pd) == 0) {
456 op->pd_id = di->inst_id;
457 DBG("Decoder of type \"%s\" has instance ID \"%s\".",
463 channels = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
464 (GDestroyNotify)g_variant_unref);
466 for (l = pd->channels; l; l = l->next) {
468 if (channel->channel > max_channel)
469 max_channel = channel->channel;
470 gvar = g_variant_new_int32(channel->channel);
471 g_variant_ref_sink(gvar);
472 g_hash_table_insert(channels, channel->name, gvar);
475 if (srd_inst_channel_set_all(di, channels) != SRD_OK)
477 g_hash_table_destroy(channels);
481 * If this is not the first decoder in the list, stack it
482 * on top of the previous one.
485 if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
486 ERR("Failed to stack decoder instances.");
493 * Bail out if we haven't created an instance of the selected
494 * decoder type of which we shall grab output data from.
499 /* Resolve selected decoder's class index, so we can match. */
500 dec = srd_decoder_get_by_id(pd->name);
502 if (op->type == SRD_OUTPUT_ANN)
503 l = dec->annotations;
504 else if (op->type == SRD_OUTPUT_BINARY)
507 /* Only annotations and binary can have a class. */
511 decoder_class = l->data;
512 if (!strcmp(decoder_class[0], op->class)) {
519 if (op->class_idx == -1) {
520 ERR("Output class '%s' not found in decoder %s.",
521 op->class, pd->name);
524 DBG("Class %s index is %d", op->class, op->class_idx);
527 sr_session_start(sr_sess);
528 sr_session_run(sr_sess);
529 sr_session_stop(sr_sess);
531 srd_session_destroy(sess);
539 static PyObject *start_coverage(GSList *pdlist)
541 PyObject *py_mod, *py_pdlist, *py_pd, *py_func, *py_args, *py_kwargs, *py_cov;
545 DBG("Starting coverage.");
547 if (!(py_mod = PyImport_ImportModule("coverage")))
550 if (!(py_pdlist = PyList_New(0)))
552 for (l = pdlist; l; l = l->next) {
554 py_pd = PyUnicode_FromFormat("*/%s/*.py", pd->name);
555 if (PyList_Append(py_pdlist, py_pd) < 0)
559 if (!(py_func = PyObject_GetAttrString(py_mod, "coverage")))
561 if (!(py_args = PyTuple_New(0)))
563 if (!(py_kwargs = Py_BuildValue("{sO}", "include", py_pdlist)))
565 if (!(py_cov = PyObject_Call(py_func, py_args, py_kwargs)))
567 if (!(PyObject_CallMethod(py_cov, "start", NULL)))
569 Py_DecRef(py_pdlist);
571 Py_DecRef(py_kwargs);
577 static struct cvg *get_mod_cov(PyObject *py_cov, const char *module_name)
579 PyObject *py_mod, *py_pathlist, *py_path, *py_func, *py_pd;
580 PyObject *py_result, *py_missed, *py_item;
584 int num_lines, num_missed, linenum, i, j;
585 char *path, *linespec;
587 if (!(py_mod = PyImport_ImportModule(module_name)))
591 py_pathlist = PyObject_GetAttrString(py_mod, "__path__");
592 for (i = 0; i < PyList_Size(py_pathlist); i++) {
593 py_path = PyList_GetItem(py_pathlist, i);
594 PyUnicode_FSConverter(PyList_GetItem(py_pathlist, i), &py_path);
595 path = PyBytes_AS_STRING(py_path);
596 if (!(d = opendir(path))) {
597 ERR("Invalid module path '%s'", path);
600 while ((de = readdir(d))) {
601 if (strncmp(de->d_name + strlen(de->d_name) - 3, ".py", 3))
604 if (!(py_func = PyObject_GetAttrString(py_cov, "analysis2")))
606 if (!(py_pd = PyUnicode_FromFormat("%s/%s", path, de->d_name)))
608 if (!(py_result = PyObject_CallFunction(py_func, "O", py_pd)))
615 if (PyTuple_Size(py_result) != 5) {
616 ERR("Invalid result from coverage of '%s/%s'", path, de->d_name);
619 num_lines = PyList_Size(PyTuple_GetItem(py_result, 1));
620 py_missed = PyTuple_GetItem(py_result, 3);
621 num_missed = PyList_Size(py_missed);
622 cvg_mod->num_lines += num_lines;
623 cvg_mod->num_missed += num_missed;
624 for (j = 0; j < num_missed; j++) {
625 py_item = PyList_GetItem(py_missed, j);
626 linenum = PyLong_AsLong(py_item);
627 linespec = g_strdup_printf("%s/%s:%d", module_name,
628 de->d_name, linenum);
629 cvg_mod->missed_lines = g_slist_append(cvg_mod->missed_lines, linespec);
631 DBG("Coverage for %s/%s: %d lines, %d missed.",
632 module_name, de->d_name, num_lines, num_missed);
633 Py_DecRef(py_result);
636 if (cvg_mod->num_lines)
637 cvg_mod->coverage = 100 - ((float)cvg_mod->num_missed / (float)cvg_mod->num_lines * 100);
645 static struct cvg *cvg_new(void)
649 cvg = calloc(1, sizeof(struct cvg));
654 static gboolean find_missed_line(struct cvg *cvg, const char *linespec)
658 for (l = cvg->missed_lines; l; l = l->next)
659 if (!strcmp(l->data, linespec))
665 static void cvg_add(struct cvg *dst, const struct cvg *src)
670 dst->num_lines += src->num_lines;
671 dst->num_missed += src->num_missed;
672 for (l = src->missed_lines; l; l = l->next) {
674 if (!find_missed_line(dst, linespec))
675 dst->missed_lines = g_slist_append(dst->missed_lines, linespec);
680 static int report_coverage(PyObject *py_cov, GSList *pdlist)
682 PyObject *py_func, *py_mod, *py_args, *py_kwargs, *py_outfile, *py_pct;
685 struct cvg *cvg_mod, *cvg_all;
686 float total_coverage;
687 int lines, missed, cnt;
689 DBG("Making coverage report.");
691 /* Get coverage for each module in the stack. */
694 for (cnt = 0, l = pdlist; l; l = l->next, cnt++) {
696 if (!(cvg_mod = get_mod_cov(py_cov, pd->name)))
698 printf("coverage: scope=%s coverage=%.0f%% lines=%d missed=%d "
699 "missed_lines=", pd->name, cvg_mod->coverage,
700 cvg_mod->num_lines, cvg_mod->num_missed);
701 for (ml = cvg_mod->missed_lines; ml; ml = ml->next) {
702 if (ml != cvg_mod->missed_lines)
704 printf("%s", (char *)ml->data);
707 lines += cvg_mod->num_lines;
708 missed += cvg_mod->num_missed;
709 cvg_add(cvg_all, cvg_mod);
710 DBG("Coverage for module %s: %d lines, %d missed", pd->name,
711 cvg_mod->num_lines, cvg_mod->num_missed);
715 total_coverage = 100 - ((float)missed / (float)lines * 100);
717 /* Machine-readable stats on stdout. */
718 printf("coverage: scope=all coverage=%.0f%% lines=%d missed=%d\n",
719 total_coverage, cvg_all->num_lines, cvg_all->num_missed);
721 /* Write text report to file. */
722 /* io.open(coverage_report, "w") */
723 if (!(py_mod = PyImport_ImportModule("io")))
725 if (!(py_func = PyObject_GetAttrString(py_mod, "open")))
727 if (!(py_args = PyTuple_New(0)))
729 if (!(py_kwargs = Py_BuildValue("{ssss}", "file", coverage_report,
732 if (!(py_outfile = PyObject_Call(py_func, py_args, py_kwargs)))
734 Py_DecRef(py_kwargs);
737 /* py_cov.report(file=py_outfile) */
738 if (!(py_func = PyObject_GetAttrString(py_cov, "report")))
740 if (!(py_kwargs = Py_BuildValue("{sO}", "file", py_outfile)))
742 if (!(py_pct = PyObject_Call(py_func, py_args, py_kwargs)))
745 Py_DecRef(py_kwargs);
748 /* py_outfile.close() */
749 if (!(py_func = PyObject_GetAttrString(py_outfile, "close")))
751 if (!PyObject_Call(py_func, py_args, NULL))
753 Py_DecRef(py_outfile);
761 int main(int argc, char **argv)
766 struct channel *channel;
767 struct option *option;
770 char *opt_infile, **kv, **opstr;
772 op = malloc(sizeof(struct output));
784 while ((c = getopt(argc, argv, "dP:p:o:i:O:f:c:S")) != -1) {
790 pd = g_malloc(sizeof(struct pd));
791 pd->name = g_strdup(optarg);
792 pd->channels = pd->options = NULL;
793 pdlist = g_slist_append(pdlist, pd);
797 if (g_slist_length(pdlist) == 0) {
798 /* No previous -P. */
799 ERR("Syntax error at '%s'", optarg);
802 kv = g_strsplit(optarg, "=", 0);
803 if (!kv[0] || (!kv[1] || kv[2])) {
805 ERR("Syntax error at '%s'", optarg);
810 channel = malloc(sizeof(struct channel));
811 channel->name = g_strdup(kv[0]);
812 channel->channel = strtoul(kv[1], NULL, 10);
813 /* Apply to last PD. */
814 pd->channels = g_slist_append(pd->channels, channel);
816 option = malloc(sizeof(struct option));
817 option->key = g_strdup(kv[0]);
818 option->value = g_variant_new_string(kv[1]);
819 g_variant_ref_sink(option->value);
820 /* Apply to last PD. */
821 pd->options = g_slist_append(pd->options, option);
828 opstr = g_strsplit(optarg, ":", 0);
829 if (!opstr[0] || !opstr[1]) {
830 /* Need at least abc:def. */
831 ERR("Syntax error at '%s'", optarg);
835 op->pd = g_strdup(opstr[0]);
836 if (!strcmp(opstr[1], "annotation"))
837 op->type = SRD_OUTPUT_ANN;
838 else if (!strcmp(opstr[1], "binary"))
839 op->type = SRD_OUTPUT_BINARY;
840 else if (!strcmp(opstr[1], "python"))
841 op->type = SRD_OUTPUT_PYTHON;
842 else if (!strcmp(opstr[1], "exception"))
843 /* Doesn't matter, we just need it to bomb out. */
844 op->type = SRD_OUTPUT_PYTHON;
846 ERR("Unknown output type '%s'", opstr[1]);
851 op->class = g_strdup(opstr[2]);
855 op->outfile = g_strdup(optarg);
859 coverage_report = optarg;
870 if (g_slist_length(pdlist) == 0)
874 if (!op->pd || op->type == -1)
877 sr_log_callback_set(sr_log, NULL);
878 if (sr_init(&ctx) != SR_OK)
881 srd_log_callback_set(srd_log, NULL);
882 if (srd_init(DECODERS_DIR) != SRD_OK)
885 if (coverage_report) {
886 if (!(coverage = start_coverage(pdlist))) {
887 DBG("Failed to start coverage.");
888 if (PyErr_Occurred()) {
896 if (!run_testcase(opt_infile, pdlist, op))
900 DBG("Stopping coverage.");
902 if (!(PyObject_CallMethod(coverage, "stop", NULL)))
903 ERR("Failed to stop coverage.");
904 else if (!(report_coverage(coverage, pdlist)))
905 ERR("Failed to make coverage report.");
907 DBG("Coverage report in %s", coverage_report);
909 if (PyErr_Occurred()) {