]> sigrok.org Git - libsigrokdecode.git/blob - controller.c
845208a7c2f5041a9e471ba101f58b932ecb56c0
[libsigrokdecode.git] / controller.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "sigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "sigrokdecode-internal.h"
23 #include "config.h"
24 #include <glib.h>
25 #include <inttypes.h>
26 #include <stdlib.h>
27
28
29 /* List of decoder instances. */
30 static GSList *di_list = NULL;
31
32 /* List of frontend callbacks to receive PD output. */
33 static GSList *callbacks = NULL;
34
35 /* lives in decoder.c */
36 extern GSList *pd_list;
37
38 /* lives in module_sigrokdecode.c */
39 extern PyMODINIT_FUNC PyInit_sigrokdecode(void);
40
41 /* lives in type_logic.c */
42 extern PyTypeObject srd_logic_type;
43
44
45 /**
46  * Initialize libsigrokdecode.
47  *
48  * This initializes the Python interpreter, and creates and initializes
49  * a "sigrok" Python module with a single put() method.
50  *
51  * Then, it searches for sigrok protocol decoder files (*.py) in the
52  * "decoders" subdirectory of the the sigrok installation directory.
53  * All decoders that are found are loaded into memory and added to an
54  * internal list of decoders, which can be queried via srd_list_decoders().
55  *
56  * The caller is responsible for calling the clean-up function srd_exit(),
57  * which will properly shut down libsigrokdecode and free its allocated memory.
58  *
59  * Multiple calls to srd_init(), without calling srd_exit() in between,
60  * are not allowed.
61  *
62  * @return SRD_OK upon success, a (negative) error code otherwise.
63  *         Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
64  *         directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
65  *         If not enough memory could be allocated, return SRD_ERR_MALLOC.
66  */
67 int srd_init(void)
68 {
69         int ret;
70
71         srd_dbg("srd: initializing");
72
73         /* Add our own module to the list of built-in modules. */
74         PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
75
76         /* Initialize the python interpreter. */
77         Py_Initialize();
78
79         if ((ret = set_modulepath()) != SRD_OK) {
80                 Py_Finalize();
81                 return ret;
82         }
83
84         if ((ret = srd_load_all_decoders()) != SRD_OK) {
85                 Py_Finalize();
86                 return ret;
87         }
88
89         return SRD_OK;
90 }
91
92
93 /**
94  * Shutdown libsigrokdecode.
95  *
96  * This frees all the memory allocated for protocol decoders and shuts down
97  * the Python interpreter.
98  *
99  * This function should only be called if there was a (successful!) invocation
100  * of srd_init() before. Calling this function multiple times in a row, without
101  * any successful srd_init() calls in between, is not allowed.
102  *
103  * @return SRD_OK upon success, a (negative) error code otherwise.
104  */
105 int srd_exit(void)
106 {
107
108         srd_dbg("srd: exiting");
109
110         srd_unload_all_decoders();
111         g_slist_free(pd_list);
112
113         /* Py_Finalize() returns void, any finalization errors are ignored. */
114         Py_Finalize();
115
116         return SRD_OK;
117 }
118
119
120 /**
121  * Add search directories for the protocol decoders.
122  *
123  * TODO: add path from env var SIGROKDECODE_PATH, config etc
124  * TODO: Should take directoryname/path as input.
125  */
126 int set_modulepath(void)
127 {
128         int ret;
129         gchar *path, *s;
130
131 #ifdef _WIN32
132         gchar **splitted;
133
134         /*
135          * On Windows/MinGW, Python's sys.path needs entries of the form
136          * 'C:\\foo\\bar' instead of '/foo/bar'.
137          */
138
139         splitted = g_strsplit(DECODERS_DIR, "/", 0);
140         path = g_build_pathv("\\\\", splitted);
141         g_strfreev(splitted);
142 #else
143         path = g_strdup(DECODERS_DIR);
144 #endif
145
146         /* TODO: Prepend instead of appending. */
147         /* TODO: Sanity check on 'path' (length, escape special chars, ...). */
148         s = g_strdup_printf("import sys; sys.path.append(r'%s')", path);
149
150         ret = PyRun_SimpleString(s);
151
152         g_free(path);
153         g_free(s);
154
155         return ret;
156 }
157
158
159 /**
160  * Set options in a decoder instance.
161  *
162  * @param di Decoder instance.
163  * @param options A GHashTable of options to set.
164  *
165  * Handled options are removed from the hash.
166  *
167  * @return SRD_OK upon success, a (negative) error code otherwise.
168  */
169 int srd_instance_set_options(struct srd_decoder_instance *di,
170                 GHashTable *options)
171 {
172         PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
173         PyObject *py_optlist, *py_classval;
174         Py_UNICODE *py_ustr;
175         unsigned long long int val_ull;
176         int num_optkeys, ret, size, i;
177         char *key, *value;
178
179         if(!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
180                 /* Decoder has no options. */
181                 if (g_hash_table_size(options) == 0) {
182                         /* No options provided. */
183                         return SRD_OK;
184                 } else {
185                         srd_err("Protocol decoder has no options.");
186                         return SRD_ERR_ARG;
187                 }
188                 return SRD_OK;
189         }
190
191         ret = SRD_ERR_PYTHON;
192         key = NULL;
193         py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
194         py_optlist = py_classval = NULL;
195         py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");
196
197         /* All of these are synthesized objects, so they're good. */
198         py_dec_optkeys = PyDict_Keys(py_dec_options);
199         num_optkeys = PyList_Size(py_dec_optkeys);
200         if (!(py_di_options = PyObject_GetAttrString(di->py_instance, "options")))
201                 goto err_out;
202         for (i = 0; i < num_optkeys; i++) {
203                 /* Get the default class value for this option. */
204                 py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
205                 if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
206                         goto err_out;
207                 if (!(py_classval = PyList_GetItem(py_optlist, 1)))
208                         goto err_out;
209                 if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) {
210                         srd_err("Options of type %s are not yet supported.", Py_TYPE(py_classval)->tp_name);
211                         goto err_out;
212                 }
213
214                 if ((value = g_hash_table_lookup(options, key))) {
215                         /* An override for this option was provided. */
216                         if (PyUnicode_Check(py_classval)) {
217                                 if (!(py_optval = PyUnicode_FromString(value))) {
218                                         /* Some UTF-8 encoding error. */
219                                         PyErr_Clear();
220                                         goto err_out;
221                                 }
222                         } else if (PyLong_Check(py_classval)) {
223                                 if (!(py_optval = PyLong_FromString(value, NULL, 0))) {
224                                         /* ValueError Exception */
225                                         PyErr_Clear();
226                                         srd_err("Option %s has invalid value %s: expected integer.",
227                                                         key, value);
228                                         goto err_out;
229                                 }
230                         }
231                         g_hash_table_remove(options, key);
232                 } else {
233                         /* Use the class default for this option. */
234                         if (PyUnicode_Check(py_classval)) {
235                                 /* Make a brand new copy of the string. */
236                                 py_ustr = PyUnicode_AS_UNICODE(py_classval);
237                                 size = PyUnicode_GET_SIZE(py_classval);
238                                 py_optval = PyUnicode_FromUnicode(py_ustr, size);
239                         } else if (PyLong_Check(py_classval)) {
240                                 /* Make a brand new copy of the integer. */
241                                 val_ull = PyLong_AsUnsignedLongLong(py_classval);
242                                 if (val_ull == (unsigned long long)-1) {
243                                         /* OverFlowError exception */
244                                         PyErr_Clear();
245                                         srd_err("Invalid integer value for %s: expected integer.", key);
246                                         goto err_out;
247                                 }
248                                 if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
249                                         goto err_out;
250                         }
251                 }
252
253                 /* If we got here, py_optval holds a known good new reference
254                  * to the instance option to set.
255                  */
256                 if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
257                         goto err_out;
258         }
259
260         ret = SRD_OK;
261
262 err_out:
263         Py_XDECREF(py_optlist);
264         Py_XDECREF(py_di_options);
265         Py_XDECREF(py_dec_optkeys);
266         Py_XDECREF(py_dec_options);
267         if (key)
268                 g_free(key);
269         if (PyErr_Occurred())
270                 catch_exception("srd: stray exception in srd_instance_set_options()");
271
272         return ret;
273 }
274
275 /* Helper GComparefunc for g_slist_find_custom() in srd_instance_set_probes() */
276 static gint compare_probe_id(struct srd_probe *a, char *probe_id)
277 {
278
279         return strcmp(a->id, probe_id);
280 }
281
282 /**
283  * Set probes in a decoder instance.
284  *
285  * @param di Decoder instance.
286  * @param probes A GHashTable of probes to set. Key is probe name, value is
287  * the probe number. Samples passed to this instance will be arranged in this
288  * order.
289  *
290  * @return SRD_OK upon success, a (negative) error code otherwise.
291  */
292 int srd_instance_set_probes(struct srd_decoder_instance *di,
293                 GHashTable *new_probes)
294 {
295         GList *l;
296         GSList *sl;
297         struct srd_probe *p;
298         int *new_probemap, new_probenum;
299         char *probe_id, *probenum_str;
300
301         if (g_hash_table_size(new_probes) == 0)
302                 /* No probes provided. */
303                 return SRD_OK;
304
305         if(di->dec_num_probes == 0) {
306                 /* Decoder has no probes. */
307                 srd_err("Protocol decoder %s has no probes to define.",
308                                 di->decoder->name);
309                 return SRD_ERR_ARG;
310         }
311
312         new_probemap = NULL;
313
314         if (!(new_probemap = g_try_malloc(sizeof(int) * di->dec_num_probes))) {
315                 srd_err("Failed to malloc new probe map.");
316                 return SRD_ERR_MALLOC;
317         }
318
319         for (l = g_hash_table_get_keys(new_probes); l; l = l->next) {
320                 probe_id = l->data;
321                 probenum_str = g_hash_table_lookup(new_probes, probe_id);
322                 if (!probenum_str) {
323                         /* Probe name was specified without a value. */
324                         srd_err("No probe number was specified for %s.", probe_id);
325                         g_free(new_probemap);
326                         return SRD_ERR_ARG;
327                 }
328                 new_probenum = strtol(probenum_str, NULL, 10);
329                 if (!(sl = g_slist_find_custom(di->decoder->probes, probe_id,
330                                 (GCompareFunc)compare_probe_id))) {
331                         /* Fall back on optional probes. */
332                         if (!(sl = g_slist_find_custom(di->decoder->extra_probes,
333                                         probe_id, (GCompareFunc)compare_probe_id))) {
334                                 srd_err("Protocol decoder %s has no probe '%s'.",
335                                                 di->decoder->name, probe_id);
336                                 g_free(new_probemap);
337                                 return SRD_ERR_ARG;
338                         }
339                 }
340                 p = sl->data;
341                 new_probemap[p->order] = new_probenum;
342         }
343         g_free(di->dec_probemap);
344         di->dec_probemap = new_probemap;
345
346         return SRD_OK;
347 }
348
349 /**
350  * Create a new protocol decoder instance.
351  *
352  * @param id Decoder 'id' field.
353  * @param options GHashtable of options which override the defaults set in
354  *          the decoder class.
355  * @return Pointer to a newly allocated struct srd_decoder_instance, or
356  *              NULL in case of failure.
357  */
358 struct srd_decoder_instance *srd_instance_new(const char *decoder_id,
359                 GHashTable *options)
360 {
361         struct srd_decoder *dec;
362         struct srd_decoder_instance *di;
363         int i;
364         char *instance_id;
365
366         srd_dbg("srd: creating new %s instance", decoder_id);
367
368         if (!(dec = srd_get_decoder_by_id(decoder_id))) {
369                 srd_err("Protocol decoder %s not found.", decoder_id);
370                 return NULL;
371         }
372
373         if (!(di = g_try_malloc0(sizeof(*di)))) {
374                 srd_err("Failed to malloc instance.");
375                 return NULL;
376         }
377
378         instance_id = g_hash_table_lookup(options, "id");
379         di->decoder = dec;
380         di->instance_id = g_strdup(instance_id ? instance_id : decoder_id);
381         g_hash_table_remove(options, "id");
382
383         /* Prepare a default probe map, where samples come in the
384          * order in which the decoder class defined them.
385          */
386         di->dec_num_probes = g_slist_length(di->decoder->probes) +
387                         g_slist_length(di->decoder->extra_probes);
388         if (di->dec_num_probes) {
389                 if (!(di->dec_probemap = g_try_malloc(sizeof(int) * di->dec_num_probes))) {
390                         srd_err("Failed to malloc probe map.");
391                         g_free(di);
392                         return NULL;
393                 }
394                 for (i = 0; i < di->dec_num_probes; i++)
395                         di->dec_probemap[i] = i;
396         }
397
398         /* Create a new instance of this decoder class. */
399         if (!(di->py_instance = PyObject_CallObject(dec->py_dec, NULL))) {
400                 if (PyErr_Occurred())
401                         catch_exception("failed to create %s instance: ", decoder_id);
402                 g_free(di->dec_probemap);
403                 g_free(di);
404                 return NULL;
405         }
406
407         if (srd_instance_set_options(di, options) != SRD_OK) {
408                 g_free(di->dec_probemap);
409                 g_free(di);
410                 return NULL;
411         }
412
413         /* Instance takes input from a frontend by default. */
414         di_list = g_slist_append(di_list, di);
415
416         return di;
417 }
418
419 int srd_instance_stack(struct srd_decoder_instance *di_from,
420                 struct srd_decoder_instance *di_to)
421 {
422
423         if (!di_from || !di_to) {
424                 srd_err("Invalid from/to instance pair.");
425                 return SRD_ERR_ARG;
426         }
427
428         if (!g_slist_find(di_list, di_from)) {
429                 srd_err("Unstacked instance not found.");
430                 return SRD_ERR_ARG;
431         }
432
433         /* Remove from the unstacked list. */
434         di_list = g_slist_remove(di_list, di_to);
435
436         /* Stack on top of source di. */
437         di_from->next_di = g_slist_append(di_from->next_di, di_to);
438
439         return SRD_OK;
440 }
441
442
443 /* TODO: this should go into the PD stack */
444 struct srd_decoder_instance *srd_instance_find(char *instance_id)
445 {
446         GSList *l;
447         struct srd_decoder_instance *tmp, *di;
448
449         di = NULL;
450         for (l = di_list; l; l = l->next) {
451                 tmp = l->data;
452                 if (!strcmp(tmp->instance_id, instance_id)) {
453                         di = tmp;
454                         break;
455                 }
456         }
457
458         return di;
459 }
460
461 int srd_instance_start(struct srd_decoder_instance *di, PyObject *args)
462 {
463         PyObject *py_name, *py_res;
464
465         srd_dbg("srd: calling start() method on protocol decoder instance %s",
466                         di->instance_id);
467
468         if (!(py_name = PyUnicode_FromString("start"))) {
469                 srd_err("Unable to build python object for 'start'.");
470                 catch_exception("Protocol decoder instance %s: ", di->instance_id);
471                 return SRD_ERR_PYTHON;
472         }
473
474         if (!(py_res = PyObject_CallMethodObjArgs(di->py_instance,
475                         py_name, args, NULL))) {
476                 catch_exception("Protocol decoder instance %s: ", di->instance_id);
477                 return SRD_ERR_PYTHON;
478         }
479
480         Py_DecRef(py_res);
481         Py_DecRef(py_name);
482
483         return SRD_OK;
484 }
485
486 /**
487  * Run the specified decoder function.
488  *
489  * @param start_samplenum The starting sample number for the buffer's sample
490  *              set, relative to the start of capture.
491  * @param di The decoder instance to call.
492  * @param inbuf The buffer to decode.
493  * @param inbuflen Length of the buffer.
494  *
495  * @return SRD_OK upon success, a (negative) error code otherwise.
496  */
497 int srd_instance_decode(uint64_t start_samplenum,
498                 struct srd_decoder_instance *di, uint8_t *inbuf, uint64_t inbuflen)
499 {
500         PyObject *py_res;
501         srd_logic *logic;
502         uint64_t end_samplenum;
503
504         srd_dbg("srd: calling decode() on instance %s with %d bytes starting "
505                         "at sample %d", di->instance_id, inbuflen, start_samplenum);
506
507         /* Return an error upon unusable input. */
508         if (di == NULL) {
509                 srd_dbg("srd: empty decoder instance");
510                 return SRD_ERR_ARG;
511         }
512         if (inbuf == NULL) {
513                 srd_dbg("srd: NULL buffer pointer");
514                 return SRD_ERR_ARG;
515         }
516         if (inbuflen == 0) {
517                 srd_dbg("srd: empty buffer");
518                 return SRD_ERR_ARG;
519         }
520
521         /* Create new srd_logic object. Each iteration around the PD's loop
522          * will fill one sample into this object.
523          */
524         logic = PyObject_New(srd_logic, &srd_logic_type);
525         Py_INCREF(logic);
526         logic->di = di;
527         logic->start_samplenum = start_samplenum;
528         logic->itercnt = 0;
529         logic->inbuf = inbuf;
530         logic->inbuflen = inbuflen;
531         logic->sample = PyList_New(2);
532         Py_INCREF(logic->sample);
533
534         Py_IncRef(di->py_instance);
535         end_samplenum = start_samplenum + inbuflen / di->data_unitsize;
536         if (!(py_res = PyObject_CallMethod(di->py_instance, "decode",
537                         "KKO", logic->start_samplenum, end_samplenum, logic))) {
538                 catch_exception("Protocol decoder instance %s: ", di->instance_id);
539                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
540         }
541         Py_DecRef(py_res);
542
543         return SRD_OK;
544 }
545
546
547 int srd_session_start(int num_probes, int unitsize, uint64_t samplerate)
548 {
549         PyObject *args;
550         GSList *d, *s;
551         struct srd_decoder_instance *di;
552         int ret;
553
554         srd_dbg("srd: calling start() on all instances with %d probes, "
555                         "unitsize %d samplerate %d", num_probes, unitsize, samplerate);
556
557         /* Currently only one item of metadata is passed along to decoders,
558          * samplerate. This can be extended as needed.
559          */
560         if (!(args = Py_BuildValue("{s:l}", "samplerate", (long)samplerate))) {
561                 srd_err("Unable to build python object for metadata.");
562                 return SRD_ERR_PYTHON;
563         }
564
565         /* Run the start() method on all decoders receiving frontend data. */
566         for (d = di_list; d; d = d->next) {
567                 di = d->data;
568                 di->data_num_probes = num_probes;
569                 di->data_unitsize = unitsize;
570                 di->data_samplerate = samplerate;
571                 if ((ret = srd_instance_start(di, args) != SRD_OK))
572                         return ret;
573
574                 /* Run the start() method on all decoders up the stack from this one. */
575                 for (s = di->next_di; s; s = s->next) {
576                         /* These don't need probes, unitsize and samplerate. */
577                         di = s->data;
578                         if ((ret = srd_instance_start(di, args) != SRD_OK))
579                                 return ret;
580                 }
581         }
582
583         Py_DecRef(args);
584
585         return SRD_OK;
586 }
587
588 /* Feed logic samples to decoder session. */
589 int srd_session_feed(uint64_t start_samplenum, uint8_t *inbuf, uint64_t inbuflen)
590 {
591         GSList *d;
592         int ret;
593
594         srd_dbg("srd: calling decode() on all instances with starting sample "
595                         "number %"PRIu64", %"PRIu64" bytes at 0x%p", start_samplenum,
596                         inbuflen, inbuf);
597
598         for (d = di_list; d; d = d->next) {
599                 if ((ret = srd_instance_decode(start_samplenum, d->data, inbuf,
600                                 inbuflen)) != SRD_OK)
601                         return ret;
602         }
603
604         return SRD_OK;
605 }
606
607
608 int srd_register_callback(int output_type, void *cb)
609 {
610         struct srd_pd_callback *pd_cb;
611
612         srd_dbg("srd: registering new callback for output type %d", output_type);
613
614         if (!(pd_cb = g_try_malloc(sizeof(struct srd_pd_callback))))
615                 return SRD_ERR_MALLOC;
616
617         pd_cb->output_type = output_type;
618         pd_cb->callback = cb;
619         callbacks = g_slist_append(callbacks, pd_cb);
620
621         return SRD_OK;
622 }
623
624 void *srd_find_callback(int output_type)
625 {
626         GSList *l;
627         struct srd_pd_callback *pd_cb;
628         void *(cb);
629
630         cb = NULL;
631         for (l = callbacks; l; l = l->next) {
632                 pd_cb = l->data;
633                 if (pd_cb->output_type == output_type) {
634                         cb = pd_cb->callback;
635                         break;
636                 }
637         }
638
639         return cb;
640 }
641
642
643 /* This is the backend function to python sigrokdecode.add() call. */
644 int pd_add(struct srd_decoder_instance *di, int output_type,
645                 char *proto_id)
646 {
647         struct srd_pd_output *pdo;
648
649         srd_dbg("srd: instance %s creating new output type %d for %s",
650                         di->instance_id, output_type, proto_id);
651
652         if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output))))
653                 return -1;
654
655         /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
656         pdo->pdo_id = g_slist_length(di->pd_output);
657         pdo->output_type = output_type;
658         pdo->decoder = di->decoder;
659         pdo->proto_id = g_strdup(proto_id);
660         di->pd_output = g_slist_append(di->pd_output, pdo);
661
662         return pdo->pdo_id;
663 }
664
665 struct srd_decoder_instance *get_di_by_decobject(void *decobject)
666 {
667         GSList *l, *s;
668         struct srd_decoder_instance *di;
669
670         for (l = di_list; l; l = l->next) {
671                 di = l->data;
672                 if (decobject == di->py_instance)
673                         return di;
674                 /* Check decoders stacked on top of this one. */
675                 for (s = di->next_di; s; s = s->next) {
676                         di = s->data;
677                         if (decobject == di->py_instance)
678                                 return di;
679                 }
680         }
681
682         return NULL;
683 }
684