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-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include "libsigrokdecode.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 of pointers to struct srd_decoder items.
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 pdch = g_malloc(sizeof(struct srd_channel));
137 if ((py_dictitem_as_str(py_entry, "id", &pdch->id)) != SRD_OK) {
138 ret = SRD_ERR_PYTHON;
141 if ((py_dictitem_as_str(py_entry, "name", &pdch->name)) != SRD_OK) {
142 ret = SRD_ERR_PYTHON;
145 if ((py_dictitem_as_str(py_entry, "desc", &pdch->desc)) != SRD_OK) {
146 ret = SRD_ERR_PYTHON;
151 *pdchl = g_slist_append(*pdchl, pdch);
154 Py_DecRef(py_channellist);
159 static int get_options(struct srd_decoder *d)
161 PyObject *py_opts, *py_opt, *py_val, *py_default, *py_item;
163 struct srd_decoder_option *o;
170 if (!PyObject_HasAttrString(d->py_dec, "options"))
171 /* No options, that's fine. */
174 /* If present, options must be a tuple. */
175 py_opts = PyObject_GetAttrString(d->py_dec, "options");
176 if (!PyTuple_Check(py_opts)) {
177 srd_err("Protocol decoder %s: options attribute is not "
179 return SRD_ERR_PYTHON;
182 for (opt = 0; opt < PyTuple_Size(py_opts); opt++) {
183 py_opt = PyTuple_GetItem(py_opts, opt);
184 if (!PyDict_Check(py_opt)) {
185 srd_err("Protocol decoder %s options: each option "
186 "must consist of a dictionary.", d->name);
187 return SRD_ERR_PYTHON;
189 if (!(py_val = PyDict_GetItemString(py_opt, "id"))) {
190 srd_err("Protocol decoder %s option %d has no "
192 return SRD_ERR_PYTHON;
194 o = g_malloc0(sizeof(struct srd_decoder_option));
195 py_str_as_str(py_val, &o->id);
197 if ((py_val = PyDict_GetItemString(py_opt, "desc")))
198 py_str_as_str(py_val, &o->desc);
200 if ((py_default = PyDict_GetItemString(py_opt, "default"))) {
201 if (PyUnicode_Check(py_default)) {
203 py_str_as_str(py_default, &sval);
204 o->def = g_variant_new_string(sval);
206 } else if (PyLong_Check(py_default)) {
208 lval = PyLong_AsLongAndOverflow(py_default, &overflow);
210 /* Value is < LONG_MIN or > LONG_MAX */
212 srd_err("Protocol decoder %s option 'default' has "
213 "invalid default value.", d->name);
214 return SRD_ERR_PYTHON;
216 o->def = g_variant_new_int64(lval);
217 } else if (PyFloat_Check(py_default)) {
219 if ((dval = PyFloat_AsDouble(py_default)) == -1.0) {
221 srd_err("Protocol decoder %s option 'default' has "
222 "invalid default value.", d->name);
223 return SRD_ERR_PYTHON;
225 o->def = g_variant_new_double(dval);
227 srd_err("Protocol decoder %s option 'default' has "
228 "value of unsupported type '%s'.", d->name,
229 Py_TYPE(py_default)->tp_name);
230 return SRD_ERR_PYTHON;
232 g_variant_ref_sink(o->def);
235 if ((py_val = PyDict_GetItemString(py_opt, "values"))) {
236 /* A default is required if a list of values is
237 * given, since it's used to verify their type. */
239 srd_err("No default for option '%s'", o->id);
240 return SRD_ERR_PYTHON;
242 if (!PyTuple_Check(py_val)) {
243 srd_err("Option '%s' values should be a tuple.", o->id);
244 return SRD_ERR_PYTHON;
246 for (i = 0; i < PyTuple_Size(py_val); i++) {
247 py_item = PyTuple_GetItem(py_val, i);
248 if (Py_TYPE(py_default) != Py_TYPE(py_item)) {
249 srd_err("All values for option '%s' must be "
250 "of the same type as the default.",
252 return SRD_ERR_PYTHON;
254 if (PyUnicode_Check(py_item)) {
256 py_str_as_str(py_item, &sval);
257 gvar = g_variant_new_string(sval);
258 g_variant_ref_sink(gvar);
260 o->values = g_slist_append(o->values, gvar);
261 } else if (PyLong_Check(py_item)) {
263 lval = PyLong_AsLongAndOverflow(py_item, &overflow);
265 /* Value is < LONG_MIN or > LONG_MAX */
267 srd_err("Protocol decoder %s option 'values' "
268 "has invalid value.", d->name);
269 return SRD_ERR_PYTHON;
271 gvar = g_variant_new_int64(lval);
272 g_variant_ref_sink(gvar);
273 o->values = g_slist_append(o->values, gvar);
274 } else if (PyFloat_Check(py_item)) {
276 if ((dval = PyFloat_AsDouble(py_item)) == -1.0) {
278 srd_err("Protocol decoder %s option 'default' has "
279 "invalid default value.", d->name);
280 return SRD_ERR_PYTHON;
282 gvar = g_variant_new_double(dval);
283 g_variant_ref_sink(gvar);
284 o->values = g_slist_append(o->values, gvar);
288 d->options = g_slist_append(d->options, o);
295 * Load a protocol decoder module into the embedded Python interpreter.
297 * @param module_name The module name to be loaded.
299 * @return SRD_OK upon success, a (negative) error code otherwise.
303 SRD_API int srd_decoder_load(const char *module_name)
305 PyObject *py_basedec, *py_method, *py_attr, *py_annlist, *py_ann;
306 PyObject *py_bin_classes, *py_bin_class, *py_ann_rows, *py_ann_row;
307 PyObject *py_ann_classes, *py_long;
308 struct srd_decoder *d;
310 char **ann, **bin, *ann_row_id, *ann_row_desc;
311 struct srd_channel *pdch;
312 GSList *l, *ann_classes;
313 struct srd_decoder_annotation_row *ann_row;
315 if (!srd_check_init())
321 if (PyDict_GetItemString(PyImport_GetModuleDict(), module_name)) {
322 /* Module was already imported. */
326 srd_dbg("Loading protocol decoder '%s'.", module_name);
328 py_basedec = py_method = py_attr = NULL;
330 d = g_malloc0(sizeof(struct srd_decoder));
332 ret = SRD_ERR_PYTHON;
334 /* Import the Python module. */
335 if (!(d->py_mod = PyImport_ImportModule(module_name))) {
336 srd_exception_catch("Import of '%s' failed.", module_name);
340 /* Get the 'Decoder' class as Python object. */
341 if (!(d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder"))) {
342 /* This generated an AttributeError exception. */
344 srd_err("Decoder class not found in protocol decoder %s.",
349 if (!(py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder"))) {
350 srd_dbg("sigrokdecode module not loaded.");
354 if (!PyObject_IsSubclass(d->py_dec, py_basedec)) {
355 srd_err("Decoder class in protocol decoder module %s is not "
356 "a subclass of sigrokdecode.Decoder.", module_name);
359 Py_CLEAR(py_basedec);
362 * Check that this decoder has the correct PD API version.
363 * PDs of different API versions are incompatible and cannot work.
365 py_long = PyObject_GetAttrString(d->py_dec, "api_version");
366 if (PyLong_AsLong(py_long) != 2) {
367 srd_err("Only PDs of API version 2 are supported.");
372 /* Check for a proper start() method. */
373 if (!PyObject_HasAttrString(d->py_dec, "start")) {
374 srd_err("Protocol decoder %s has no start() method Decoder "
375 "class.", module_name);
378 py_method = PyObject_GetAttrString(d->py_dec, "start");
379 if (!PyFunction_Check(py_method)) {
380 srd_err("Protocol decoder %s Decoder class attribute 'start' "
381 "is not a method.", module_name);
386 /* Check for a proper decode() method. */
387 if (!PyObject_HasAttrString(d->py_dec, "decode")) {
388 srd_err("Protocol decoder %s has no decode() method Decoder "
389 "class.", module_name);
392 py_method = PyObject_GetAttrString(d->py_dec, "decode");
393 if (!PyFunction_Check(py_method)) {
394 srd_err("Protocol decoder %s Decoder class attribute 'decode' "
395 "is not a method.", module_name);
400 /* Store required fields in newly allocated strings. */
401 if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK)
404 if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK)
407 if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK)
410 if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK)
413 if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK)
416 /* All options and their default values. */
417 if (get_options(d) != SRD_OK)
420 /* Check and import required channels. */
421 if (get_channels(d, "channels", &d->channels) != SRD_OK)
424 /* Check and import optional channels. */
425 if (get_channels(d, "optional_channels", &d->opt_channels) != SRD_OK)
429 * Fix order numbers for the optional channels.
432 * Required channels: r1, r2, r3. Optional: o1, o2, o3, o4.
433 * 'order' fields in the d->channels list = 0, 1, 2.
434 * 'order' fields in the d->opt_channels list = 3, 4, 5, 6.
436 for (l = d->opt_channels; l; l = l->next) {
438 pdch->order += g_slist_length(d->channels);
441 /* Convert annotation class attribute to GSList of char **. */
442 d->annotations = NULL;
443 if (PyObject_HasAttrString(d->py_dec, "annotations")) {
444 py_annlist = PyObject_GetAttrString(d->py_dec, "annotations");
445 if (!PyTuple_Check(py_annlist)) {
446 srd_err("Protocol decoder %s annotations should "
447 "be a tuple.", module_name);
450 for (i = 0; i < PyTuple_Size(py_annlist); i++) {
451 py_ann = PyTuple_GetItem(py_annlist, i);
452 if (!PyTuple_Check(py_ann) || PyTuple_Size(py_ann) != 2) {
453 srd_err("Protocol decoder %s annotation %d should "
454 "be a tuple with two elements.", module_name, i + 1);
458 if (py_strseq_to_char(py_ann, &ann) != SRD_OK) {
461 d->annotations = g_slist_append(d->annotations, ann);
465 /* Convert annotation_rows to GSList of 'struct srd_decoder_annotation_row'. */
466 d->annotation_rows = NULL;
467 if (PyObject_HasAttrString(d->py_dec, "annotation_rows")) {
468 py_ann_rows = PyObject_GetAttrString(d->py_dec, "annotation_rows");
469 if (!PyTuple_Check(py_ann_rows)) {
470 srd_err("Protocol decoder %s annotation row list "
471 "must be a tuple.", module_name);
474 for (i = 0; i < PyTuple_Size(py_ann_rows); i++) {
475 py_ann_row = PyTuple_GetItem(py_ann_rows, i);
476 if (!PyTuple_Check(py_ann_row)) {
477 srd_err("Protocol decoder %s annotation rows "
478 "must be tuples.", module_name);
481 if (PyTuple_Size(py_ann_row) != 3
482 || !PyUnicode_Check(PyTuple_GetItem(py_ann_row, 0))
483 || !PyUnicode_Check(PyTuple_GetItem(py_ann_row, 1))
484 || !PyTuple_Check(PyTuple_GetItem(py_ann_row, 2))) {
485 srd_err("Protocol decoder %s annotation rows "
486 "must contain tuples containing two "
487 "strings and a tuple.", module_name);
491 if (py_str_as_str(PyTuple_GetItem(py_ann_row, 0), &ann_row_id) != SRD_OK)
494 if (py_str_as_str(PyTuple_GetItem(py_ann_row, 1), &ann_row_desc) != SRD_OK)
497 py_ann_classes = PyTuple_GetItem(py_ann_row, 2);
499 for (j = 0; j < PyTuple_Size(py_ann_classes); j++) {
500 py_long = PyTuple_GetItem(py_ann_classes, j);
501 if (!PyLong_Check(py_long)) {
502 srd_err("Protocol decoder %s annotation row class "
503 "list must only contain numbers.", module_name);
506 ann_classes = g_slist_append(ann_classes,
507 GINT_TO_POINTER(PyLong_AsLong(py_long)));
510 ann_row = g_malloc0(sizeof(struct srd_decoder_annotation_row));
511 ann_row->id = ann_row_id;
512 ann_row->desc = ann_row_desc;
513 ann_row->ann_classes = ann_classes;
514 d->annotation_rows = g_slist_append(d->annotation_rows, ann_row);
518 /* Convert binary class to GSList of char *. */
520 if (PyObject_HasAttrString(d->py_dec, "binary")) {
521 py_bin_classes = PyObject_GetAttrString(d->py_dec, "binary");
522 if (!PyTuple_Check(py_bin_classes)) {
523 srd_err("Protocol decoder %s binary classes should "
524 "be a tuple.", module_name);
527 for (i = 0; i < PyTuple_Size(py_bin_classes); i++) {
528 py_bin_class = PyTuple_GetItem(py_bin_classes, i);
529 if (!PyTuple_Check(py_bin_class)) {
530 srd_err("Protocol decoder %s binary classes "
531 "should consist of tuples.", module_name);
534 if (PyTuple_Size(py_bin_class) != 2
535 || !PyUnicode_Check(PyTuple_GetItem(py_bin_class, 0))
536 || !PyUnicode_Check(PyTuple_GetItem(py_bin_class, 1))) {
537 srd_err("Protocol decoder %s binary classes should "
538 "contain tuples with two strings.", module_name);
542 if (py_strseq_to_char(py_bin_class, &bin) != SRD_OK) {
545 d->binary = g_slist_append(d->binary, bin);
549 /* Append it to the list of supported/loaded decoders. */
550 pd_list = g_slist_append(pd_list, d);
556 Py_XDECREF(py_method);
557 Py_XDECREF(py_basedec);
558 Py_XDECREF(d->py_dec);
559 Py_XDECREF(d->py_mod);
567 * Return a protocol decoder's docstring.
569 * @param dec The loaded protocol decoder.
571 * @return A newly allocated buffer containing the protocol decoder's
572 * documentation. The caller is responsible for free'ing the buffer.
576 SRD_API char *srd_decoder_doc_get(const struct srd_decoder *dec)
581 if (!srd_check_init())
587 if (!PyObject_HasAttrString(dec->py_mod, "__doc__"))
590 if (!(py_str = PyObject_GetAttrString(dec->py_mod, "__doc__"))) {
591 srd_exception_catch("");
596 if (py_str != Py_None)
597 py_str_as_str(py_str, &doc);
603 static void free_channels(GSList *channellist)
606 struct srd_channel *pdch;
608 if (channellist == NULL)
611 for (l = channellist; l; l = l->next) {
618 g_slist_free(channellist);
622 * Unload the specified protocol decoder.
624 * @param dec The struct srd_decoder to be unloaded.
626 * @return SRD_OK upon success, a (negative) error code otherwise.
630 SRD_API int srd_decoder_unload(struct srd_decoder *dec)
632 struct srd_decoder_option *o;
633 struct srd_session *sess;
636 if (!srd_check_init())
642 srd_dbg("Unloading protocol decoder '%s'.", dec->name);
645 * Since any instances of this decoder need to be released as well,
646 * but they could be anywhere in the stack, just free the entire
647 * stack. A frontend reloading a decoder thus has to restart all
648 * instances, and rebuild the stack.
650 for (l = sessions; l; l = l->next) {
652 srd_inst_free_all(sess, NULL);
655 for (l = dec->options; l; l = l->next) {
659 g_variant_unref(o->def);
662 g_slist_free(dec->options);
664 free_channels(dec->channels);
665 free_channels(dec->opt_channels);
668 g_free(dec->longname);
670 g_free(dec->license);
672 /* The module's Decoder class. */
673 Py_XDECREF(dec->py_dec);
674 /* The module itself. */
675 Py_XDECREF(dec->py_mod);
682 static void srd_decoder_load_all_zip_path(char *path)
684 PyObject *zipimport_mod, *zipimporter_class, *zipimporter;
685 PyObject *prefix_obj, *files, *key, *value, *set, *modname;
690 set = files = prefix_obj = zipimporter = zipimporter_class = NULL;
692 zipimport_mod = PyImport_ImportModule("zipimport");
693 if (zipimport_mod == NULL)
696 zipimporter_class = PyObject_GetAttrString(zipimport_mod, "zipimporter");
697 if (zipimporter_class == NULL)
700 zipimporter = PyObject_CallFunction(zipimporter_class, "s", path);
701 if (zipimporter == NULL)
704 prefix_obj = PyObject_GetAttrString(zipimporter, "prefix");
705 if (prefix_obj == NULL)
708 files = PyObject_GetAttrString(zipimporter, "_files");
712 set = PySet_New(NULL);
716 if (py_str_as_str(prefix_obj, &prefix) != SRD_OK)
719 prefix_len = strlen(prefix);
721 while (PyDict_Next(files, &pos, &key, &value)) {
723 if (py_str_as_str(key, &path) == SRD_OK) {
724 if (strlen(path) > prefix_len &&
725 !memcmp(path, prefix, prefix_len) &&
726 (slash = strchr(path+prefix_len, '/'))) {
728 PyUnicode_FromStringAndSize(path+prefix_len,
729 slash-(path+prefix_len));
730 if (modname == NULL) {
733 PySet_Add(set, modname);
743 while ((modname = PySet_Pop(set))) {
745 if (py_str_as_str(modname, &modname_str) == SRD_OK) {
746 /* The directory name is the module name (e.g. "i2c"). */
747 srd_decoder_load(modname_str);
756 Py_XDECREF(prefix_obj);
757 Py_XDECREF(zipimporter);
758 Py_XDECREF(zipimporter_class);
759 Py_XDECREF(zipimport_mod);
763 static void srd_decoder_load_all_path(char *path)
766 const gchar *direntry;
768 if (!(dir = g_dir_open(path, 0, NULL))) {
769 /* Not really fatal */
770 /* Try zipimport method too */
771 srd_decoder_load_all_zip_path(path);
775 /* This ignores errors returned by srd_decoder_load(). That
776 * function will have logged the cause, but in any case we
777 * want to continue anyway. */
778 while ((direntry = g_dir_read_name(dir)) != NULL) {
779 /* The directory name is the module name (e.g. "i2c"). */
780 srd_decoder_load(direntry);
787 * Load all installed protocol decoders.
789 * @return SRD_OK upon success, a (negative) error code otherwise.
793 SRD_API int srd_decoder_load_all(void)
797 if (!srd_check_init())
800 for (l = searchpaths; l; l = l->next)
801 srd_decoder_load_all_path(l->data);
807 * Unload all loaded protocol decoders.
809 * @return SRD_OK upon success, a (negative) error code otherwise.
813 SRD_API int srd_decoder_unload_all(void)
816 struct srd_decoder *dec;
818 for (l = pd_list; l; l = l->next) {
820 srd_decoder_unload(dec);
822 g_slist_free(pd_list);