runtc: Output binary as ASCII timestamp/class/hex bytes instead.
[libsigrokdecode.git] / tests / runtc.c
1 /*
2  * This file is part of the libsigrokdecode 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 "../libsigrokdecode.h"
21 #include <libsigrok/libsigrok.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stdarg.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <time.h>
31 #include <sys/time.h>
32 #include <sys/resource.h>
33 #include <glib.h>
34 #ifdef __LINUX__
35 #include <sched.h>
36 #endif
37 #include "../config.h"
38
39
40 int debug = FALSE;
41 int statistics = FALSE;
42
43 struct probe {
44         char *name;
45         int probe;
46 };
47
48 struct option {
49         char *key;
50         char *value;
51 };
52
53 struct pd {
54         char *name;
55         GSList *probes;
56         GSList *options;
57 };
58
59 struct output {
60         char *pd;
61         int type;
62         char *class;
63         int class_idx;
64         char *outfile;
65         int outfd;
66 };
67
68
69 void logmsg(char *prefix, FILE *out, const char *format, va_list args)
70 {
71         if (prefix)
72                 fprintf(out, "%s", prefix);
73         vfprintf(out, format, args);
74         fprintf(out, "\n");
75 }
76
77 void DBG(const char *format, ...)
78 {
79         va_list args;
80
81         if (!debug)
82                 return;
83         va_start(args, format);
84         logmsg("DBG: ", stdout, format, args);
85         va_end(args);
86 }
87
88 void ERR(const char *format, ...)
89 {
90         va_list args;
91
92         va_start(args, format);
93         logmsg("Error: ", stderr, format, args);
94         va_end(args);
95 }
96
97 int sr_log(void *cb_data, int loglevel, const char *format, va_list args)
98 {
99         (void)cb_data;
100
101         if (loglevel == SR_LOG_ERR || loglevel == SR_LOG_WARN)
102                 logmsg("Error: sr: ", stderr, format, args);
103         else if (debug)
104                 logmsg("DBG: sr: ", stdout, format, args);
105
106         return SRD_OK;
107 }
108
109 int srd_log(void *cb_data, int loglevel, const char *format, va_list args)
110 {
111         (void)cb_data;
112
113         if (loglevel == SRD_LOG_ERR || loglevel == SRD_LOG_WARN)
114                 logmsg("Error: srd: ", stderr, format, args);
115         else if (debug)
116                 logmsg("DBG: srd: ", stdout, format, args);
117
118         return SRD_OK;
119 }
120
121 void usage(char *msg)
122 {
123         if (msg)
124                 fprintf(stderr, "%s\n", msg);
125
126         printf("Usage: runtc [-dPpoiOf]\n");
127         printf("  -d  Debug\n");
128         printf("  -P  <protocol decoder>\n");
129         printf("  -p  <probename=probenum> (optional)\n");
130         printf("  -o  <probeoption=value> (optional)\n");
131         printf("  -i <input file>\n");
132         printf("  -O <output-pd:output-type[:output-class]>\n");
133         printf("  -f <output file> (optional)\n");
134         exit(msg ? 1 : 0);
135
136 }
137
138 /* This is a neutered version of libsigrokdecode's py_str_as_str(). It
139  * does no error checking, but then the only strings it processes are
140  * generated by Python's repr(), so are known good. */
141 char *py_str_as_str(const PyObject *py_str)
142 {
143         PyObject *py_encstr;
144         char *str, *outstr;
145
146         py_encstr = PyUnicode_AsEncodedString((PyObject *)py_str, "utf-8", NULL);
147         str = PyBytes_AS_STRING(py_encstr);
148         outstr = g_strdup(str);
149         Py_DecRef(py_encstr);
150
151         return outstr;
152 }
153
154 static void srd_cb_py(struct srd_proto_data *pdata, void *cb_data)
155 {
156         struct output *op;
157         PyObject *pydata, *pyrepr;
158         GString *out;
159         char *s;
160
161         DBG("Python output from %s", pdata->pdo->di->inst_id);
162         op = cb_data;
163         pydata = pdata->data;
164         DBG("ptr %p", pydata);
165
166         if (strcmp(pdata->pdo->di->inst_id, op->pd))
167                 /* This is not the PD selected for output. */
168                 return;
169
170         if (!(pyrepr = PyObject_Repr(pydata))) {
171                 ERR("Invalid Python object.");
172                 return;
173         }
174         s = py_str_as_str(pyrepr);
175         Py_DecRef(pyrepr);
176
177         /* Output format for testing is '<ss>-<es> <inst-id>: <repr>\n' */
178         out = g_string_sized_new(128);
179         g_string_printf(out, "%"PRIu64"-%"PRIu64" %s: %s\n",
180                         pdata->start_sample, pdata->end_sample,
181                         pdata->pdo->di->inst_id, s);
182         g_free(s);
183         if (write(op->outfd, out->str, out->len) == -1)
184                 ERR("SRD_OUTPUT_PYTHON callback write failure!");
185         DBG("wrote '%s'", out->str);
186         g_string_free(out, TRUE);
187
188 }
189
190 static void srd_cb_bin(struct srd_proto_data *pdata, void *cb_data)
191 {
192         struct srd_proto_data_binary *pdb;
193         struct output *op;
194         GString *out;
195         unsigned int i;
196
197         DBG("Binary output from %s", pdata->pdo->di->inst_id);
198         op = cb_data;
199         pdb = pdata->data;
200
201         if (strcmp(pdata->pdo->di->inst_id, op->pd))
202                 /* This is not the PD selected for output. */
203                 return;
204
205         if (op->class_idx != -1 && op->class_idx != pdb->bin_class)
206                 /*
207                  * This output takes a specific binary class,
208                  * but not the one that just came in.
209                  */
210                 return;
211
212         out = g_string_sized_new(128);
213         g_string_printf(out, "%"PRIu64"-%"PRIu64" %s:",
214                         pdata->start_sample, pdata->end_sample,
215                         pdata->pdo->di->inst_id);
216         for (i = 0; i < pdb->size; i++) {
217                 g_string_append_printf(out, " %.2x", pdb->data[i]);
218         }
219         g_string_append(out, "\n");
220         if (write(op->outfd, out->str, out->len) == -1)
221                 ERR("SRD_OUTPUT_BINARY callback write failure!");
222
223 }
224
225 static void srd_cb_ann(struct srd_proto_data *pdata, void *cb_data)
226 {
227         struct srd_decoder *dec;
228         struct srd_proto_data_annotation *pda;
229         struct output *op;
230         GString *line;
231         int i;
232         char **dec_ann;
233
234         DBG("Annotation output from %s", pdata->pdo->di->inst_id);
235         op = cb_data;
236         pda = pdata->data;
237         dec = pdata->pdo->di->decoder;
238         if (strcmp(pdata->pdo->di->inst_id, op->pd))
239                 /* This is not the PD selected for output. */
240                 return;
241
242         if (op->class_idx != -1 && op->class_idx != pda->ann_format)
243                 /*
244                  * This output takes a specific annotation class,
245                  * but not the one that just came in.
246                  */
247                 return;
248
249         dec_ann = g_slist_nth_data(dec->annotations, pda->ann_format);
250         line = g_string_sized_new(256);
251         g_string_printf(line, "%"PRIu64"-%"PRIu64" %s: %s:",
252                         pdata->start_sample, pdata->end_sample,
253                         pdata->pdo->di->inst_id, dec_ann[0]);
254         for (i = 0; pda->ann_text[i]; i++)
255                 g_string_append_printf(line, " \"%s\"", pda->ann_text[i]);
256         g_string_append(line, "\n");
257         if (write(op->outfd, line->str, line->len) == -1)
258                 ERR("SRD_OUTPUT_ANN callback write failure!");
259         g_string_free(line, TRUE);
260
261 }
262
263 static void sr_cb(const struct sr_dev_inst *sdi,
264                 const struct sr_datafeed_packet *packet, void *cb_data)
265 {
266         const struct sr_datafeed_logic *logic;
267         struct srd_session *sess;
268         GVariant *gvar;
269         uint64_t samplerate;
270         int num_samples;
271         static int samplecnt = 0;
272
273         sess = cb_data;
274
275         switch (packet->type) {
276         case SR_DF_HEADER:
277                 DBG("Received SR_DF_HEADER");
278                 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
279                                 &gvar) != SR_OK) {
280                         ERR("Getting samplerate failed");
281                         break;
282                 }
283                 samplerate = g_variant_get_uint64(gvar);
284                 g_variant_unref(gvar);
285                 if (srd_session_metadata_set(sess, SRD_CONF_SAMPLERATE,
286                                 g_variant_new_uint64(samplerate)) != SRD_OK) {
287                         ERR("Setting samplerate failed");
288                         break;
289                 }
290                 if (srd_session_start(sess) != SRD_OK) {
291                         ERR("Session start failed");
292                         break;
293                 }
294                 break;
295         case SR_DF_LOGIC:
296                 logic = packet->payload;
297                 num_samples = logic->length / logic->unitsize;
298                 DBG("Received SR_DF_LOGIC: %d samples", num_samples);
299                 srd_session_send(sess, samplecnt, samplecnt + num_samples,
300                                 logic->data, logic->length);
301                 samplecnt += logic->length / logic->unitsize;
302                 break;
303         case SR_DF_END:
304                 DBG("Received SR_DF_END");
305                 break;
306         }
307
308 }
309
310 int get_stats(int stats[2])
311 {
312         FILE *f;
313         size_t len;
314         int tmp;
315         char *buf;
316
317         stats[0] = stats[1] = -1;
318         if (!(f = fopen("/proc/self/status", "r")))
319                 return FALSE;
320         len = 128;
321         buf = malloc(len);
322         while (getline(&buf, &len, f) != -1) {
323                 if (strcasestr(buf, "vmpeak:")) {
324                         stats[0] = strtoul(buf + 10, NULL, 10);
325                 } else if (strcasestr(buf, "vmsize:")) {
326                         tmp = strtoul(buf + 10, NULL, 10);
327                         if (tmp > stats[0])
328                                 stats[0] = tmp;
329                 } else if (strcasestr(buf, "vmhwm:")) {
330                         stats[1] = strtoul(buf + 6, NULL, 10);
331                 } else if (strcasestr(buf, "vmrss:")) {
332                         tmp = strtoul(buf + 10, NULL, 10);
333                         if (tmp > stats[0])
334                                 stats[0] = tmp;
335                 }
336         }
337         free(buf);
338         fclose(f);
339
340         return TRUE;
341 }
342
343 static int run_testcase(char *infile, GSList *pdlist, struct output *op)
344 {
345         struct srd_session *sess;
346         struct srd_decoder *dec;
347         struct srd_decoder_inst *di, *prev_di;
348         srd_pd_output_callback_t cb;
349         struct pd *pd;
350         struct probe *probe;
351         struct option *option;
352         GVariant *gvar;
353         GHashTable *probes, *opts;
354         GSList *pdl, *l;
355         int idx;
356         char **decoder_class;
357
358         if (op->outfile) {
359                 if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
360                         ERR("Unable to open %s for writing: %s", op->outfile,
361                                         strerror(errno));
362                         return FALSE;
363                 }
364         }
365
366         if (sr_session_load(infile) != SR_OK)
367                 return FALSE;
368
369         if (srd_session_new(&sess) != SRD_OK)
370                 return FALSE;
371         sr_session_datafeed_callback_add(sr_cb, sess);
372         switch (op->type) {
373         case SRD_OUTPUT_ANN:
374                 cb = srd_cb_ann;
375                 break;
376         case SRD_OUTPUT_BINARY:
377                 cb = srd_cb_bin;
378                 break;
379         case SRD_OUTPUT_PYTHON:
380                 cb = srd_cb_py;
381                 break;
382         default:
383                 return FALSE;
384         }
385         srd_pd_output_callback_add(sess, op->type, cb, op);
386
387         prev_di = NULL;
388         pd = NULL;
389         for (pdl = pdlist; pdl; pdl = pdl->next) {
390                 pd = pdl->data;
391                 if (srd_decoder_load(pd->name) != SRD_OK)
392                         return FALSE;
393
394                 /* Instantiate decoder and pass in options. */
395                 opts = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
396                                 (GDestroyNotify)g_variant_unref);
397                 for (l = pd->options; l; l = l->next) {
398                         option = l->data;
399                         g_hash_table_insert(opts, option->key, option->value);
400                 }
401                 if (!(di = srd_inst_new(sess, pd->name, opts)))
402                         return FALSE;
403                 g_hash_table_destroy(opts);
404
405                 /* Map probes. */
406                 if (pd->probes) {
407                         probes = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
408                                         (GDestroyNotify)g_variant_unref);
409                         for (l = pd->probes; l; l = l->next) {
410                                 probe = l->data;
411                                 gvar = g_variant_new_int32(probe->probe);
412                                 g_variant_ref_sink(gvar);
413                                 g_hash_table_insert(probes, probe->name, gvar);
414                         }
415                         if (srd_inst_probe_set_all(di, probes) != SRD_OK)
416                                 return FALSE;
417                         g_hash_table_destroy(probes);
418                 }
419
420                 /* If this is not the first decoder in the list, stack it
421                  * on top of the previous one. */
422                 if (prev_di) {
423                         if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
424                                 ERR("Failed to stack decoder instances.");
425                                 return FALSE;
426                         }
427                 }
428                 prev_di = di;
429         }
430
431         /* Resolve top decoder's class index, so we can match. */
432         dec = srd_decoder_get_by_id(pd->name);
433         if (op->class) {
434                 if (op->type == SRD_OUTPUT_ANN)
435                         l = dec->annotations;
436                 else if (op->type == SRD_OUTPUT_BINARY)
437                         l = dec->binary;
438                 else
439                         /* Only annotations and binary can have a class. */
440                         return FALSE;
441                 idx = 0;
442                 while(l) {
443                         decoder_class = l->data;
444                         if (!strcmp(decoder_class[0], op->class)) {
445                                 op->class_idx = idx;
446                                 break;
447                         } else
448                                 idx++;
449                         l = l->next;
450                 }
451                 if (op->class_idx == -1) {
452                         ERR("Output class '%s' not found in decoder %s.",
453                                         op->class, pd->name);
454                         return FALSE;
455                 } else
456                         DBG("Class %s index is %d", op->class, op->class_idx);
457         }
458
459         sr_session_start();
460         sr_session_run();
461         sr_session_stop();
462
463         srd_session_destroy(sess);
464
465         if (op->outfile)
466                 close(op->outfd);
467
468         return TRUE;
469 }
470
471 int main(int argc, char **argv)
472 {
473         struct sr_context *ctx;
474         GSList *pdlist;
475         struct pd *pd;
476         struct probe *probe;
477         struct option *option;
478         struct output *op;
479         int ret;
480         char c, *opt_infile, **kv, **opstr;
481
482         op = malloc(sizeof(struct output));
483         op->pd = NULL;
484         op->type = -1;
485         op->class = NULL;
486         op->class_idx = -1;
487         op->outfd = 1;
488
489         pdlist = NULL;
490         opt_infile = NULL;
491         pd = NULL;
492         while((c = getopt(argc, argv, "dP:p:o:i:O:f:S")) != -1) {
493                 switch(c) {
494                 case 'd':
495                         debug = TRUE;
496                         break;
497                 case 'P':
498                         pd = g_malloc(sizeof(struct pd));
499                         pd->name = g_strdup(optarg);
500                         pd->probes = pd->options = NULL;
501                         pdlist = g_slist_append(pdlist, pd);
502                         break;
503                 case 'p':
504                 case 'o':
505                         if (g_slist_length(pdlist) == 0) {
506                                 /* No previous -P. */
507                                 ERR("Syntax error at '%s'", optarg);
508                                 usage(NULL);
509                         }
510                         kv = g_strsplit(optarg, "=", 0);
511                         if (!kv[0] || (!kv[1] || kv[2])) {
512                                 /* Need x=y. */
513                                 ERR("Syntax error at '%s'", optarg);
514                                 g_strfreev(kv);
515                                 usage(NULL);
516                         }
517                         if (c == 'p') {
518                                 probe = malloc(sizeof(struct probe));
519                                 probe->name = g_strdup(kv[0]);
520                                 probe->probe = strtoul(kv[1], 0, 10);
521                                 /* Apply to last PD. */
522                                 pd->probes = g_slist_append(pd->probes, probe);
523                         } else {
524                                 option = malloc(sizeof(struct option));
525                                 option->key = g_strdup(kv[0]);
526                                 option->value = g_strdup(kv[1]);
527                                 /* Apply to last PD. */
528                                 pd->options = g_slist_append(pd->options, option);
529                         }
530                         break;
531                 case 'i':
532                         opt_infile = optarg;
533                         break;
534                 case 'O':
535                         opstr = g_strsplit(optarg, ":", 0);
536                         if (!opstr[0] || !opstr[1]) {
537                                 /* Need at least abc:def. */
538                                 ERR("Syntax error at '%s'", optarg);
539                                 g_strfreev(opstr);
540                                 usage(NULL);
541                         }
542                         op->pd = g_strdup(opstr[0]);
543                         if (!strcmp(opstr[1], "annotation"))
544                                 op->type = SRD_OUTPUT_ANN;
545                         else if (!strcmp(opstr[1], "binary"))
546                                 op->type = SRD_OUTPUT_BINARY;
547                         else if (!strcmp(opstr[1], "python"))
548                                 op->type = SRD_OUTPUT_PYTHON;
549                         else {
550                                 ERR("Unknown output type '%s'", opstr[1]);
551                                 g_strfreev(opstr);
552                                 usage(NULL);
553                         }
554                         if (opstr[2])
555                                 op->class = g_strdup(opstr[2]);
556                         g_strfreev(opstr);
557                         break;
558                 case 'f':
559                         op->outfile = g_strdup(optarg);
560                         op->outfd = -1;
561                         break;
562                 case 'S':
563                         statistics = TRUE;
564                         break;
565                 default:
566                         usage(NULL);
567                 }
568         }
569         if (argc > optind)
570                 usage(NULL);
571         if (g_slist_length(pdlist) == 0)
572                 usage(NULL);
573         if (!opt_infile)
574                 usage(NULL);
575         if (!op->pd || op->type == -1)
576                 usage(NULL);
577
578         sr_log_callback_set(sr_log, NULL);
579         if (sr_init(&ctx) != SR_OK)
580                 return 1;
581
582         srd_log_callback_set(srd_log, NULL);
583         if (srd_init(DECODERS_DIR) != SRD_OK)
584                 return 1;
585
586         ret = 0;
587         if (!run_testcase(opt_infile, pdlist, op))
588                 ret = 1;
589
590         srd_exit();
591         sr_exit(ctx);
592
593         return ret;
594 }
595
596