e6266b07b30b2a5aa8fae5627e7bf5dcf1c1f3a9
[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         //while((c = getopt(argc, argv, "dP:p:o:i:O:f:S")) != -1) {
127         printf("Usage: runtc [-dPpoiOf]\n");
128         printf("  -d  Debug\n");
129         printf("  -P  <protocol decoder>\n");
130         printf("  -p  <probename=probenum> (optional)\n");
131         printf("  -o  <probeoption=value> (optional)\n");
132         printf("  -i <input file>\n");
133         printf("  -O <output-pd:output-type[:output-class]>\n");
134         printf("  -f <output file> (optional)\n");
135         exit(msg ? 1 : 0);
136
137 }
138
139 static void srd_cb_bin(struct srd_proto_data *pdata, void *cb_data)
140 {
141         struct srd_proto_data_binary *pdb;
142         struct output *op;
143
144         op = cb_data;
145         if (op->type != SRD_OUTPUT_BINARY)
146                 return;
147
148         DBG("Binary output from %s", pdata->pdo->di->inst_id);
149         pdb = pdata->data;
150
151         if (strcmp(pdata->pdo->di->inst_id, op->pd))
152                 /* This is not the PD selected for output. */
153                 return;
154
155         if (op->class_idx != -1 && op->class_idx != pdb->bin_class)
156                 /*
157                  * This output takes a specific binary class,
158                  * but not the one that just came in.
159                  */
160                 return;
161
162         if (write(op->outfd, pdb->data, pdb->size) == -1)
163                 ERR("Oops!");
164
165 }
166
167 static void srd_cb_ann(struct srd_proto_data *pdata, void *cb_data)
168 {
169         struct srd_decoder *dec;
170         struct srd_proto_data_annotation *pda;
171         struct output *op;
172         GString *line;
173         int i;
174         char **dec_ann;
175
176         op = cb_data;
177         if (op->type != SRD_OUTPUT_ANN)
178                 return;
179
180         DBG("Annotation output from %s", pdata->pdo->di->inst_id);
181         pda = pdata->data;
182         dec = pdata->pdo->di->decoder;
183         if (strcmp(pdata->pdo->di->inst_id, op->pd))
184                 /* This is not the PD selected for output. */
185                 return;
186
187         if (op->class_idx != -1 && op->class_idx != pda->ann_format)
188                 /*
189                  * This output takes a specific annotation class,
190                  * but not the one that just came in.
191                  */
192                 return;
193
194         dec_ann = g_slist_nth_data(dec->annotations, pda->ann_format);
195         line = g_string_sized_new(256);
196         g_string_printf(line, "%"PRIu64"-%"PRIu64" %s: %s:",
197                         pdata->start_sample, pdata->end_sample,
198                         pdata->pdo->di->inst_id, dec_ann[0]);
199         for (i = 0; pda->ann_text[i]; i++)
200                 g_string_append_printf(line, " \"%s\"", pda->ann_text[i]);
201         g_string_append(line, "\n");
202         if (write(op->outfd, line->str, line->len) == -1)
203                 ERR("Oops!");
204         g_string_free(line, TRUE);
205
206 }
207
208 static void sr_cb(const struct sr_dev_inst *sdi,
209                 const struct sr_datafeed_packet *packet, void *cb_data)
210 {
211         const struct sr_datafeed_logic *logic;
212         struct srd_session *sess;
213         GVariant *gvar;
214         uint64_t samplerate;
215         int num_samples;
216         static int samplecnt = 0;
217
218         sess = cb_data;
219
220         switch (packet->type) {
221         case SR_DF_HEADER:
222                 DBG("Received SR_DF_HEADER");
223                 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
224                                 &gvar) != SR_OK) {
225                         ERR("Getting samplerate failed");
226                         break;
227                 }
228                 samplerate = g_variant_get_uint64(gvar);
229                 g_variant_unref(gvar);
230                 if (srd_session_metadata_set(sess, SRD_CONF_SAMPLERATE,
231                                 g_variant_new_uint64(samplerate)) != SRD_OK) {
232                         ERR("Setting samplerate failed");
233                         break;
234                 }
235                 if (srd_session_start(sess) != SRD_OK) {
236                         ERR("Session start failed");
237                         break;
238                 }
239                 break;
240         case SR_DF_LOGIC:
241                 logic = packet->payload;
242                 num_samples = logic->length / logic->unitsize;
243                 DBG("Received SR_DF_LOGIC: %d samples", num_samples);
244                 srd_session_send(sess, samplecnt, samplecnt + num_samples,
245                                 logic->data, logic->length);
246                 samplecnt += logic->length / logic->unitsize;
247                 break;
248         case SR_DF_END:
249                 DBG("Received SR_DF_END");
250                 break;
251         }
252
253 }
254
255 int get_stats(int stats[2])
256 {
257         FILE *f;
258         size_t len;
259         int tmp;
260         char *buf;
261
262         stats[0] = stats[1] = -1;
263         if (!(f = fopen("/proc/self/status", "r")))
264                 return FALSE;
265         len = 128;
266         buf = malloc(len);
267         while (getline(&buf, &len, f) != -1) {
268                 if (strcasestr(buf, "vmpeak:")) {
269                         stats[0] = strtoul(buf + 10, NULL, 10);
270                 } else if (strcasestr(buf, "vmsize:")) {
271                         tmp = strtoul(buf + 10, NULL, 10);
272                         if (tmp > stats[0])
273                                 stats[0] = tmp;
274                 } else if (strcasestr(buf, "vmhwm:")) {
275                         stats[1] = strtoul(buf + 6, NULL, 10);
276                 } else if (strcasestr(buf, "vmrss:")) {
277                         tmp = strtoul(buf + 10, NULL, 10);
278                         if (tmp > stats[0])
279                                 stats[0] = tmp;
280                 }
281         }
282         free(buf);
283         fclose(f);
284
285         return TRUE;
286 }
287
288 static int run_testcase(char *infile, GSList *pdlist, struct output *op)
289 {
290         struct srd_session *sess;
291         struct srd_decoder *dec;
292         struct srd_decoder_inst *di, *prev_di;
293         struct pd *pd;
294         struct probe *probe;
295         struct option *option;
296         GVariant *gvar;
297         GHashTable *probes, *opts;
298         GSList *pdl, *l;
299         int idx;
300         char **decoder_class;
301
302         if (op->outfile) {
303                 if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
304                         ERR("Unable to open %s for writing: %s", op->outfile,
305                                         strerror(errno));
306                         return FALSE;
307                 }
308         }
309
310         if (sr_session_load(infile) != SR_OK)
311                 return FALSE;
312
313         if (srd_session_new(&sess) != SRD_OK)
314                 return FALSE;
315         sr_session_datafeed_callback_add(sr_cb, sess);
316         srd_pd_output_callback_add(sess, SRD_OUTPUT_ANN, srd_cb_ann, op);
317         srd_pd_output_callback_add(sess, SRD_OUTPUT_BINARY, srd_cb_bin, op);
318
319         prev_di = NULL;
320         pd = NULL;
321         for (pdl = pdlist; pdl; pdl = pdl->next) {
322                 pd = pdl->data;
323                 if (srd_decoder_load(pd->name) != SRD_OK)
324                         return FALSE;
325
326                 /* Instantiate decoder and pass in options. */
327                 opts = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
328                                 (GDestroyNotify)g_variant_unref);
329                 for (l = pd->options; l; l = l->next) {
330                         option = l->data;
331                         g_hash_table_insert(opts, option->key, option->value);
332                 }
333                 if (!(di = srd_inst_new(sess, pd->name, opts)))
334                         return FALSE;
335                 g_hash_table_destroy(opts);
336
337                 /* Map probes. */
338                 if (pd->probes) {
339                         probes = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
340                                         (GDestroyNotify)g_variant_unref);
341                         for (l = pd->probes; l; l = l->next) {
342                                 probe = l->data;
343                                 gvar = g_variant_new_int32(probe->probe);
344                                 g_variant_ref_sink(gvar);
345                                 g_hash_table_insert(probes, probe->name, gvar);
346                         }
347                         if (srd_inst_probe_set_all(di, probes) != SRD_OK)
348                                 return FALSE;
349                         g_hash_table_destroy(probes);
350                 }
351
352
353                 /* If this is not the first decoder in the list, stack it
354                  * on top of the previous one. */
355                 if (prev_di) {
356                         if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
357                                 ERR("Failed to stack decoder instances.");
358                                 return FALSE;
359                         }
360                 }
361                 prev_di = di;
362         }
363
364         /* Resolve top decoder's class index, so we can match. */
365         dec = srd_decoder_get_by_id(pd->name);
366         if (op->class) {
367                 if (op->type == SRD_OUTPUT_ANN)
368                         l = dec->annotations;
369                 else if (op->type == SRD_OUTPUT_BINARY)
370                         l = dec->binary;
371                 else
372                         /* Only annotations and binary for now. */
373                         return FALSE;
374                 idx = 0;
375                 while(l) {
376                         decoder_class = l->data;
377                         if (!strcmp(decoder_class[0], op->class)) {
378                                 op->class_idx = idx;
379                                 break;
380                         } else
381                                 idx++;
382                         l = l->next;
383                 }
384                 if (op->class_idx == -1) {
385                         ERR("Output class '%s' not found in decoder %s.",
386                                         op->class, pd->name);
387                         return FALSE;
388                 } else
389                         DBG("Class %s index is %d", op->class, op->class_idx);
390         }
391
392         sr_session_start();
393         sr_session_run();
394         sr_session_stop();
395
396         srd_session_destroy(sess);
397
398         if (op->outfile)
399                 close(op->outfd);
400
401         return TRUE;
402 }
403
404 int main(int argc, char **argv)
405 {
406         struct sr_context *ctx;
407         GSList *pdlist;
408         struct pd *pd;
409         struct probe *probe;
410         struct option *option;
411         struct output *op;
412         int ret;
413         char c, *opt_infile, **kv, **opstr;
414
415         op = malloc(sizeof(struct output));
416         op->pd = NULL;
417         op->type = -1;
418         op->class = NULL;
419         op->class_idx = -1;
420         op->outfd = 1;
421
422         pdlist = NULL;
423         opt_infile = NULL;
424         pd = NULL;
425         while((c = getopt(argc, argv, "dP:p:o:i:O:f:S")) != -1) {
426                 switch(c) {
427                 case 'd':
428                         debug = TRUE;
429                         break;
430                 case 'P':
431                         pd = g_malloc(sizeof(struct pd));
432                         pd->name = g_strdup(optarg);
433                         pd->probes = pd->options = NULL;
434                         pdlist = g_slist_append(pdlist, pd);
435                         break;
436                 case 'p':
437                 case 'o':
438                         if (g_slist_length(pdlist) == 0) {
439                                 /* No previous -P. */
440                                 ERR("Syntax error at '%s'", optarg);
441                                 usage(NULL);
442                         }
443                         kv = g_strsplit(optarg, "=", 0);
444                         if (!kv[0] || (!kv[1] || kv[2])) {
445                                 /* Need x=y. */
446                                 ERR("Syntax error at '%s'", optarg);
447                                 g_strfreev(kv);
448                                 usage(NULL);
449                         }
450                         if (c == 'p') {
451                                 probe = malloc(sizeof(struct probe));
452                                 probe->name = g_strdup(kv[0]);
453                                 probe->probe = strtoul(kv[1], 0, 10);
454                                 /* Apply to last PD. */
455                                 pd->probes = g_slist_append(pd->probes, probe);
456                         } else {
457                                 option = malloc(sizeof(struct option));
458                                 option->key = g_strdup(kv[0]);
459                                 option->value = g_strdup(kv[1]);
460                                 /* Apply to last PD. */
461                                 pd->options = g_slist_append(pd->options, option);
462                         }
463                         break;
464                 case 'i':
465                         opt_infile = optarg;
466                         break;
467                 case 'O':
468                         opstr = g_strsplit(optarg, ":", 0);
469                         if (!opstr[0] || !opstr[1]) {
470                                 /* Need at least abc:def. */
471                                 ERR("Syntax error at '%s'", optarg);
472                                 g_strfreev(opstr);
473                                 usage(NULL);
474                         }
475                         op->pd = g_strdup(opstr[0]);
476                         if (!strcmp(opstr[1], "annotation"))
477                                 op->type = SRD_OUTPUT_ANN;
478                         else if (!strcmp(opstr[1], "binary"))
479                                 op->type = SRD_OUTPUT_BINARY;
480                         else if (!strcmp(opstr[1], "python"))
481                                 op->type = SRD_OUTPUT_PYTHON;
482                         else {
483                                 ERR("Unknown output type '%s'", opstr[1]);
484                                 g_strfreev(opstr);
485                                 usage(NULL);
486                         }
487                         if (opstr[2])
488                                 op->class = g_strdup(opstr[2]);
489                         g_strfreev(opstr);
490                         break;
491                 case 'f':
492                         op->outfile = g_strdup(optarg);
493                         op->outfd = -1;
494                         break;
495                 case 'S':
496                         statistics = TRUE;
497                         break;
498                 default:
499                         usage(NULL);
500                 }
501         }
502         if (argc > optind)
503                 usage(NULL);
504         if (g_slist_length(pdlist) == 0)
505                 usage(NULL);
506         if (!opt_infile)
507                 usage(NULL);
508         if (!op->pd || op->type == -1)
509                 usage(NULL);
510
511         sr_log_callback_set(sr_log, NULL);
512         if (sr_init(&ctx) != SR_OK)
513                 return 1;
514
515         srd_log_callback_set(srd_log, NULL);
516         if (srd_init(DECODERS_DIR) != SRD_OK)
517                 return 1;
518
519         ret = 0;
520         if (!run_testcase(opt_infile, pdlist, op))
521                 ret = 1;
522
523         srd_exit();
524         sr_exit(ctx);
525
526         return ret;
527 }
528
529