2 * This file is part of the libsigrokdecode project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
22 #include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include "libsigrokdecode-internal.h"
29 * Listing, loading, unloading, and handling protocol decoders.
33 * @defgroup grp_decoder Protocol decoders
35 * Handling protocol decoders.
42 /* The list of protocol decoders. */
43 static GSList *pd_list = NULL;
46 extern SRD_PRIV GSList *searchpaths;
49 extern SRD_PRIV GSList *sessions;
50 extern SRD_PRIV int max_session_id;
52 /* module_sigrokdecode.c */
53 extern SRD_PRIV PyObject *mod_sigrokdecode;
57 static gboolean srd_check_init(void)
59 if (max_session_id < 0) {
60 srd_err("Library is not initialized.");
67 * Returns the list of supported/loaded protocol decoders.
69 * This is a GSList containing the names of the decoders as strings.
71 * @return List of decoders, NULL if none are supported or loaded.
75 SRD_API const GSList *srd_decoder_list(void)
81 * Get the decoder with the specified ID.
83 * @param id The ID string of the decoder to return.
85 * @return The decoder with the specified ID, or NULL if not found.
89 SRD_API struct srd_decoder *srd_decoder_get_by_id(const char *id)
92 struct srd_decoder *dec;
94 for (l = pd_list; l; l = l->next) {
96 if (!strcmp(dec->id, id))
103 static int get_channels(const struct srd_decoder *d, const char *attr,
106 PyObject *py_channellist, *py_entry;
107 struct srd_channel *pdch;
108 int ret, num_channels, i;
110 if (!PyObject_HasAttrString(d->py_dec, attr))
111 /* No channels of this type specified. */
114 py_channellist = PyObject_GetAttrString(d->py_dec, attr);
115 if (!PyTuple_Check(py_channellist)) {
116 srd_err("Protocol decoder %s %s attribute is not a tuple.",
118 return SRD_ERR_PYTHON;
121 if ((num_channels = PyTuple_Size(py_channellist)) == 0)
122 /* Empty channellist. */
126 for (i = 0; i < num_channels; i++) {
127 py_entry = PyTuple_GetItem(py_channellist, i);
128 if (!PyDict_Check(py_entry)) {
129 srd_err("Protocol decoder %s %s attribute is not "
130 "a list with dict elements.", d->name, attr);
131 ret = SRD_ERR_PYTHON;
135 if (!(pdch = g_try_malloc(sizeof(struct srd_channel)))) {
136 srd_err("Failed to g_malloc() struct srd_channel.");
137 ret = SRD_ERR_MALLOC;
141 if ((py_dictitem_as_str(py_entry, "id", &pdch->id)) != SRD_OK) {
142 ret = SRD_ERR_PYTHON;
145 if ((py_dictitem_as_str(py_entry, "name", &pdch->name)) != SRD_OK) {
146 ret = SRD_ERR_PYTHON;
149 if ((py_dictitem_as_str(py_entry, "desc", &pdch->desc)) != SRD_OK) {
150 ret = SRD_ERR_PYTHON;
155 *pdchl = g_slist_append(*pdchl, pdch);
158 Py_DecRef(py_channellist);
163 static int get_options(struct srd_decoder *d)
165 PyObject *py_opts, *py_opt, *py_val, *py_default, *py_item;
167 struct srd_decoder_option *o;
174 if (!PyObject_HasAttrString(d->py_dec, "options"))
175 /* No options, that's fine. */
178 /* If present, options must be a tuple. */
179 py_opts = PyObject_GetAttrString(d->py_dec, "options");
180 if (!PyTuple_Check(py_opts)) {
181 srd_err("Protocol decoder %s: options attribute is not "
183 return SRD_ERR_PYTHON;
186 for (opt = 0; opt < PyTuple_Size(py_opts); opt++) {
187 py_opt = PyTuple_GetItem(py_opts, opt);
188 if (!PyDict_Check(py_opt)) {
189 srd_err("Protocol decoder %s options: each option "
190 "must consist of a dictionary.", d->name);
191 return SRD_ERR_PYTHON;
193 if (!(py_val = PyDict_GetItemString(py_opt, "id"))) {
194 srd_err("Protocol decoder %s option %d has no "
196 return SRD_ERR_PYTHON;
198 o = g_malloc0(sizeof(struct srd_decoder_option));
199 py_str_as_str(py_val, &o->id);
201 if ((py_val = PyDict_GetItemString(py_opt, "desc")))
202 py_str_as_str(py_val, &o->desc);
204 if ((py_default = PyDict_GetItemString(py_opt, "default"))) {
205 if (PyUnicode_Check(py_default)) {
207 py_str_as_str(py_default, &sval);
208 o->def = g_variant_new_string(sval);
210 } else if (PyLong_Check(py_default)) {
212 lval = PyLong_AsLongAndOverflow(py_default, &overflow);
214 /* Value is < LONG_MIN or > LONG_MAX */
216 srd_err("Protocol decoder %s option 'default' has "
217 "invalid default value.", d->name);
218 return SRD_ERR_PYTHON;
220 o->def = g_variant_new_int64(lval);
221 } else if (PyFloat_Check(py_default)) {
223 if ((dval = PyFloat_AsDouble(py_default)) == -1.0) {
225 srd_err("Protocol decoder %s option 'default' has "
226 "invalid default value.", d->name);
227 return SRD_ERR_PYTHON;
229 o->def = g_variant_new_double(dval);
231 srd_err("Protocol decoder %s option 'default' has "
232 "value of unsupported type '%s'.", d->name,
233 Py_TYPE(py_default)->tp_name);
234 return SRD_ERR_PYTHON;
236 g_variant_ref_sink(o->def);
239 if ((py_val = PyDict_GetItemString(py_opt, "values"))) {
240 /* A default is required if a list of values is
241 * given, since it's used to verify their type. */
243 srd_err("No default for option '%s'", o->id);
244 return SRD_ERR_PYTHON;
246 if (!PyTuple_Check(py_val)) {
247 srd_err("Option '%s' values should be a tuple.", o->id);
248 return SRD_ERR_PYTHON;
250 for (i = 0; i < PyTuple_Size(py_val); i++) {
251 py_item = PyTuple_GetItem(py_val, i);
252 if (Py_TYPE(py_default) != Py_TYPE(py_item)) {
253 srd_err("All values for option '%s' must be "
254 "of the same type as the default.",
256 return SRD_ERR_PYTHON;
258 if (PyUnicode_Check(py_item)) {
260 py_str_as_str(py_item, &sval);
261 gvar = g_variant_new_string(sval);
262 g_variant_ref_sink(gvar);
264 o->values = g_slist_append(o->values, gvar);
265 } else if (PyLong_Check(py_item)) {
267 lval = PyLong_AsLongAndOverflow(py_item, &overflow);
269 /* Value is < LONG_MIN or > LONG_MAX */
271 srd_err("Protocol decoder %s option 'values' "
272 "has invalid value.", d->name);
273 return SRD_ERR_PYTHON;
275 gvar = g_variant_new_int64(lval);
276 g_variant_ref_sink(gvar);
277 o->values = g_slist_append(o->values, gvar);
278 } else if (PyFloat_Check(py_item)) {
280 if ((dval = PyFloat_AsDouble(py_item)) == -1.0) {
282 srd_err("Protocol decoder %s option 'default' has "
283 "invalid default value.", d->name);
284 return SRD_ERR_PYTHON;
286 gvar = g_variant_new_double(dval);
287 g_variant_ref_sink(gvar);
288 o->values = g_slist_append(o->values, gvar);
292 d->options = g_slist_append(d->options, o);
299 * Load a protocol decoder module into the embedded Python interpreter.
301 * @param module_name The module name to be loaded.
303 * @return SRD_OK upon success, a (negative) error code otherwise.
307 SRD_API int srd_decoder_load(const char *module_name)
309 PyObject *py_basedec, *py_method, *py_attr, *py_annlist, *py_ann;
310 PyObject *py_bin_classes, *py_bin_class, *py_ann_rows, *py_ann_row;
311 PyObject *py_ann_classes, *py_long;
312 struct srd_decoder *d;
314 char **ann, **bin, *ann_row_id, *ann_row_desc;
315 struct srd_channel *pdch;
316 GSList *l, *ann_classes;
317 struct srd_decoder_annotation_row *ann_row;
319 if (!srd_check_init())
325 if (PyDict_GetItemString(PyImport_GetModuleDict(), module_name)) {
326 /* Module was already imported. */
330 srd_dbg("Loading protocol decoder '%s'.", module_name);
332 py_basedec = py_method = py_attr = NULL;
334 if (!(d = g_try_malloc0(sizeof(struct srd_decoder)))) {
335 srd_dbg("Failed to g_malloc() struct srd_decoder.");
336 ret = SRD_ERR_MALLOC;
340 ret = SRD_ERR_PYTHON;
342 /* Import the Python module. */
343 if (!(d->py_mod = PyImport_ImportModule(module_name))) {
344 srd_exception_catch("Import of '%s' failed.", module_name);
348 /* Get the 'Decoder' class as Python object. */
349 if (!(d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder"))) {
350 /* This generated an AttributeError exception. */
352 srd_err("Decoder class not found in protocol decoder %s.",
357 if (!(py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder"))) {
358 srd_dbg("sigrokdecode module not loaded.");
362 if (!PyObject_IsSubclass(d->py_dec, py_basedec)) {
363 srd_err("Decoder class in protocol decoder module %s is not "
364 "a subclass of sigrokdecode.Decoder.", module_name);
367 Py_CLEAR(py_basedec);
369 /* Check for a proper start() method. */
370 if (!PyObject_HasAttrString(d->py_dec, "start")) {
371 srd_err("Protocol decoder %s has no start() method Decoder "
372 "class.", module_name);
375 py_method = PyObject_GetAttrString(d->py_dec, "start");
376 if (!PyFunction_Check(py_method)) {
377 srd_err("Protocol decoder %s Decoder class attribute 'start' "
378 "is not a method.", module_name);
383 /* Check for a proper decode() method. */
384 if (!PyObject_HasAttrString(d->py_dec, "decode")) {
385 srd_err("Protocol decoder %s has no decode() method Decoder "
386 "class.", module_name);
389 py_method = PyObject_GetAttrString(d->py_dec, "decode");
390 if (!PyFunction_Check(py_method)) {
391 srd_err("Protocol decoder %s Decoder class attribute 'decode' "
392 "is not a method.", module_name);
397 /* Store required fields in newly allocated strings. */
398 if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK)
401 if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK)
404 if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK)
407 if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK)
410 if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK)
413 /* All options and their default values. */
414 if (get_options(d) != SRD_OK)
417 /* Check and import required channels. */
418 if (get_channels(d, "channels", &d->channels) != SRD_OK)
421 /* Check and import optional channels. */
422 if (get_channels(d, "optional_channels", &d->opt_channels) != SRD_OK)
426 * Fix order numbers for the optional channels.
429 * Required channels: r1, r2, r3. Optional: o1, o2, o3, o4.
430 * 'order' fields in the d->channels list = 0, 1, 2.
431 * 'order' fields in the d->opt_channels list = 3, 4, 5, 6.
433 for (l = d->opt_channels; l; l = l->next) {
435 pdch->order += g_slist_length(d->channels);
438 /* Convert annotation class attribute to GSList of char **. */
439 d->annotations = NULL;
440 if (PyObject_HasAttrString(d->py_dec, "annotations")) {
441 py_annlist = PyObject_GetAttrString(d->py_dec, "annotations");
442 if (!PyTuple_Check(py_annlist)) {
443 srd_err("Protocol decoder %s annotations should "
444 "be a tuple.", module_name);
447 for (i = 0; i < PyTuple_Size(py_annlist); i++) {
448 py_ann = PyTuple_GetItem(py_annlist, i);
449 if (!PyTuple_Check(py_ann) || PyTuple_Size(py_ann) != 2) {
450 srd_err("Protocol decoder %s annotation %d should "
451 "be a tuple with two elements.", module_name, i + 1);
455 if (py_strseq_to_char(py_ann, &ann) != SRD_OK) {
458 d->annotations = g_slist_append(d->annotations, ann);
462 /* Convert annotation_rows to GSList of 'struct srd_decoder_annotation_row'. */
463 d->annotation_rows = NULL;
464 if (PyObject_HasAttrString(d->py_dec, "annotation_rows")) {
465 py_ann_rows = PyObject_GetAttrString(d->py_dec, "annotation_rows");
466 if (!PyTuple_Check(py_ann_rows)) {
467 srd_err("Protocol decoder %s annotation row list "
468 "must be a tuple.", module_name);
471 for (i = 0; i < PyTuple_Size(py_ann_rows); i++) {
472 py_ann_row = PyTuple_GetItem(py_ann_rows, i);
473 if (!PyTuple_Check(py_ann_row)) {
474 srd_err("Protocol decoder %s annotation rows "
475 "must be tuples.", module_name);
478 if (PyTuple_Size(py_ann_row) != 3
479 || !PyUnicode_Check(PyTuple_GetItem(py_ann_row, 0))
480 || !PyUnicode_Check(PyTuple_GetItem(py_ann_row, 1))
481 || !PyTuple_Check(PyTuple_GetItem(py_ann_row, 2))) {
482 srd_err("Protocol decoder %s annotation rows "
483 "must contain tuples containing two "
484 "strings and a tuple.", module_name);
488 if (py_str_as_str(PyTuple_GetItem(py_ann_row, 0), &ann_row_id) != SRD_OK)
491 if (py_str_as_str(PyTuple_GetItem(py_ann_row, 1), &ann_row_desc) != SRD_OK)
494 py_ann_classes = PyTuple_GetItem(py_ann_row, 2);
496 for (j = 0; j < PyTuple_Size(py_ann_classes); j++) {
497 py_long = PyTuple_GetItem(py_ann_classes, j);
498 if (!PyLong_Check(py_long)) {
499 srd_err("Protocol decoder %s annotation row class "
500 "list must only contain numbers.", module_name);
503 ann_classes = g_slist_append(ann_classes,
504 GINT_TO_POINTER(PyLong_AsLong(py_long)));
507 ann_row = g_malloc0(sizeof(struct srd_decoder_annotation_row));
508 ann_row->id = ann_row_id;
509 ann_row->desc = ann_row_desc;
510 ann_row->ann_classes = ann_classes;
511 d->annotation_rows = g_slist_append(d->annotation_rows, ann_row);
515 /* Convert binary class to GSList of char *. */
517 if (PyObject_HasAttrString(d->py_dec, "binary")) {
518 py_bin_classes = PyObject_GetAttrString(d->py_dec, "binary");
519 if (!PyTuple_Check(py_bin_classes)) {
520 srd_err("Protocol decoder %s binary classes should "
521 "be a tuple.", module_name);
524 for (i = 0; i < PyTuple_Size(py_bin_classes); i++) {
525 py_bin_class = PyTuple_GetItem(py_bin_classes, i);
526 if (!PyTuple_Check(py_bin_class)) {
527 srd_err("Protocol decoder %s binary classes "
528 "should consist of tuples.", module_name);
531 if (PyTuple_Size(py_bin_class) != 2
532 || !PyUnicode_Check(PyTuple_GetItem(py_bin_class, 0))
533 || !PyUnicode_Check(PyTuple_GetItem(py_bin_class, 1))) {
534 srd_err("Protocol decoder %s binary classes should "
535 "contain tuples with two strings.", module_name);
539 if (py_strseq_to_char(py_bin_class, &bin) != SRD_OK) {
542 d->binary = g_slist_append(d->binary, bin);
546 /* Append it to the list of supported/loaded decoders. */
547 pd_list = g_slist_append(pd_list, d);
553 Py_XDECREF(py_method);
554 Py_XDECREF(py_basedec);
555 Py_XDECREF(d->py_dec);
556 Py_XDECREF(d->py_mod);
564 * Return a protocol decoder's docstring.
566 * @param dec The loaded protocol decoder.
568 * @return A newly allocated buffer containing the protocol decoder's
569 * documentation. The caller is responsible for free'ing the buffer.
573 SRD_API char *srd_decoder_doc_get(const struct srd_decoder *dec)
578 if (!srd_check_init())
584 if (!PyObject_HasAttrString(dec->py_mod, "__doc__"))
587 if (!(py_str = PyObject_GetAttrString(dec->py_mod, "__doc__"))) {
588 srd_exception_catch("");
593 if (py_str != Py_None)
594 py_str_as_str(py_str, &doc);
600 static void free_channels(GSList *channellist)
603 struct srd_channel *pdch;
605 if (channellist == NULL)
608 for (l = channellist; l; l = l->next) {
615 g_slist_free(channellist);
619 * Unload the specified protocol decoder.
621 * @param dec The struct srd_decoder to be unloaded.
623 * @return SRD_OK upon success, a (negative) error code otherwise.
627 SRD_API int srd_decoder_unload(struct srd_decoder *dec)
629 struct srd_decoder_option *o;
630 struct srd_session *sess;
633 if (!srd_check_init())
639 srd_dbg("Unloading protocol decoder '%s'.", dec->name);
642 * Since any instances of this decoder need to be released as well,
643 * but they could be anywhere in the stack, just free the entire
644 * stack. A frontend reloading a decoder thus has to restart all
645 * instances, and rebuild the stack.
647 for (l = sessions; l; l = l->next) {
649 srd_inst_free_all(sess, NULL);
652 for (l = dec->options; l; l = l->next) {
656 g_variant_unref(o->def);
659 g_slist_free(dec->options);
661 free_channels(dec->channels);
662 free_channels(dec->opt_channels);
665 g_free(dec->longname);
667 g_free(dec->license);
669 /* The module's Decoder class. */
670 Py_XDECREF(dec->py_dec);
671 /* The module itself. */
672 Py_XDECREF(dec->py_mod);
679 static void srd_decoder_load_all_path(char *path)
682 const gchar *direntry;
684 if (!(dir = g_dir_open(path, 0, NULL)))
685 /* Not really fatal */
688 /* This ignores errors returned by srd_decoder_load(). That
689 * function will have logged the cause, but in any case we
690 * want to continue anyway. */
691 while ((direntry = g_dir_read_name(dir)) != NULL) {
692 /* The directory name is the module name (e.g. "i2c"). */
693 srd_decoder_load(direntry);
700 * Load all installed protocol decoders.
702 * @return SRD_OK upon success, a (negative) error code otherwise.
706 SRD_API int srd_decoder_load_all(void)
710 if (!srd_check_init())
713 for (l = searchpaths; l; l = l->next)
714 srd_decoder_load_all_path(l->data);
720 * Unload all loaded protocol decoders.
722 * @return SRD_OK upon success, a (negative) error code otherwise.
726 SRD_API int srd_decoder_unload_all(void)
729 struct srd_decoder *dec;
731 for (l = pd_list; l; l = l->next) {
733 srd_decoder_unload(dec);
735 g_slist_free(pd_list);