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 %zd has no "
191 "id.", d->name, opt);
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.", d->name);
229 return SRD_ERR_PYTHON;
231 g_variant_ref_sink(o->def);
234 if ((py_val = PyDict_GetItemString(py_opt, "values"))) {
235 /* A default is required if a list of values is
236 * given, since it's used to verify their type. */
238 srd_err("No default for option '%s'", o->id);
239 return SRD_ERR_PYTHON;
241 if (!PyTuple_Check(py_val)) {
242 srd_err("Option '%s' values should be a tuple.", o->id);
243 return SRD_ERR_PYTHON;
245 for (i = 0; i < PyTuple_Size(py_val); i++) {
246 py_item = PyTuple_GetItem(py_val, i);
247 if (Py_TYPE(py_default) != Py_TYPE(py_item)) {
248 srd_err("All values for option '%s' must be "
249 "of the same type as the default.",
251 return SRD_ERR_PYTHON;
253 if (PyUnicode_Check(py_item)) {
255 py_str_as_str(py_item, &sval);
256 gvar = g_variant_new_string(sval);
257 g_variant_ref_sink(gvar);
259 o->values = g_slist_append(o->values, gvar);
260 } else if (PyLong_Check(py_item)) {
262 lval = PyLong_AsLongAndOverflow(py_item, &overflow);
264 /* Value is < LONG_MIN or > LONG_MAX */
266 srd_err("Protocol decoder %s option 'values' "
267 "has invalid value.", d->name);
268 return SRD_ERR_PYTHON;
270 gvar = g_variant_new_int64(lval);
271 g_variant_ref_sink(gvar);
272 o->values = g_slist_append(o->values, gvar);
273 } else if (PyFloat_Check(py_item)) {
275 if ((dval = PyFloat_AsDouble(py_item)) == -1.0) {
277 srd_err("Protocol decoder %s option 'default' has "
278 "invalid default value.", d->name);
279 return SRD_ERR_PYTHON;
281 gvar = g_variant_new_double(dval);
282 g_variant_ref_sink(gvar);
283 o->values = g_slist_append(o->values, gvar);
287 d->options = g_slist_append(d->options, o);
294 * Load a protocol decoder module into the embedded Python interpreter.
296 * @param module_name The module name to be loaded.
298 * @return SRD_OK upon success, a (negative) error code otherwise.
302 SRD_API int srd_decoder_load(const char *module_name)
304 PyObject *py_basedec, *py_method, *py_attr, *py_annlist, *py_ann;
305 PyObject *py_bin_classes, *py_bin_class, *py_ann_rows, *py_ann_row;
306 PyObject *py_ann_classes, *py_long;
307 struct srd_decoder *d;
309 char **ann, **bin, *ann_row_id, *ann_row_desc;
310 struct srd_channel *pdch;
311 GSList *l, *ann_classes;
312 struct srd_decoder_annotation_row *ann_row;
314 if (!srd_check_init())
320 if (PyDict_GetItemString(PyImport_GetModuleDict(), module_name)) {
321 /* Module was already imported. */
325 srd_dbg("Loading protocol decoder '%s'.", module_name);
327 py_basedec = py_method = py_attr = NULL;
329 d = g_malloc0(sizeof(struct srd_decoder));
331 ret = SRD_ERR_PYTHON;
333 /* Import the Python module. */
334 if (!(d->py_mod = PyImport_ImportModule(module_name))) {
335 srd_exception_catch("Import of '%s' failed", module_name);
339 /* Get the 'Decoder' class as Python object. */
340 if (!(d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder"))) {
341 /* This generated an AttributeError exception. */
343 srd_err("Decoder class not found in protocol decoder %s.",
348 if (!(py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder"))) {
349 srd_dbg("sigrokdecode module not loaded.");
353 if (!PyObject_IsSubclass(d->py_dec, py_basedec)) {
354 srd_err("Decoder class in protocol decoder module %s is not "
355 "a subclass of sigrokdecode.Decoder.", module_name);
358 Py_CLEAR(py_basedec);
361 * Check that this decoder has the correct PD API version.
362 * PDs of different API versions are incompatible and cannot work.
364 py_long = PyObject_GetAttrString(d->py_dec, "api_version");
365 if (PyLong_AsLong(py_long) != 2) {
366 srd_err("Only PDs of API version 2 are supported.");
371 /* Check for a proper start() method. */
372 if (!PyObject_HasAttrString(d->py_dec, "start")) {
373 srd_err("Protocol decoder %s has no start() method Decoder "
374 "class.", module_name);
377 py_method = PyObject_GetAttrString(d->py_dec, "start");
378 if (!PyCallable_Check(py_method)) {
379 srd_err("Protocol decoder %s Decoder class attribute 'start' "
380 "is not a method.", module_name);
385 /* Check for a proper decode() method. */
386 if (!PyObject_HasAttrString(d->py_dec, "decode")) {
387 srd_err("Protocol decoder %s has no decode() method Decoder "
388 "class.", module_name);
391 py_method = PyObject_GetAttrString(d->py_dec, "decode");
392 if (!PyCallable_Check(py_method)) {
393 srd_err("Protocol decoder %s Decoder class attribute 'decode' "
394 "is not a method.", module_name);
399 /* Store required fields in newly allocated strings. */
400 if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK)
403 if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK)
406 if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK)
409 if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK)
412 if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK)
415 /* All options and their default values. */
416 if (get_options(d) != SRD_OK)
419 /* Check and import required channels. */
420 if (get_channels(d, "channels", &d->channels) != SRD_OK)
423 /* Check and import optional channels. */
424 if (get_channels(d, "optional_channels", &d->opt_channels) != SRD_OK)
428 * Fix order numbers for the optional channels.
431 * Required channels: r1, r2, r3. Optional: o1, o2, o3, o4.
432 * 'order' fields in the d->channels list = 0, 1, 2.
433 * 'order' fields in the d->opt_channels list = 3, 4, 5, 6.
435 for (l = d->opt_channels; l; l = l->next) {
437 pdch->order += g_slist_length(d->channels);
440 /* Convert annotation class attribute to GSList of char **. */
441 d->annotations = NULL;
442 if (PyObject_HasAttrString(d->py_dec, "annotations")) {
443 py_annlist = PyObject_GetAttrString(d->py_dec, "annotations");
444 if (!PyTuple_Check(py_annlist)) {
445 srd_err("Protocol decoder %s annotations should "
446 "be a tuple.", module_name);
449 for (i = 0; i < PyTuple_Size(py_annlist); i++) {
450 py_ann = PyTuple_GetItem(py_annlist, i);
451 if (!PyTuple_Check(py_ann) || PyTuple_Size(py_ann) != 2) {
452 srd_err("Protocol decoder %s annotation %d should "
453 "be a tuple with two elements.", module_name, i + 1);
457 if (py_strseq_to_char(py_ann, &ann) != SRD_OK) {
460 d->annotations = g_slist_append(d->annotations, ann);
464 /* Convert annotation_rows to GSList of 'struct srd_decoder_annotation_row'. */
465 d->annotation_rows = NULL;
466 if (PyObject_HasAttrString(d->py_dec, "annotation_rows")) {
467 py_ann_rows = PyObject_GetAttrString(d->py_dec, "annotation_rows");
468 if (!PyTuple_Check(py_ann_rows)) {
469 srd_err("Protocol decoder %s annotation row list "
470 "must be a tuple.", module_name);
473 for (i = 0; i < PyTuple_Size(py_ann_rows); i++) {
474 py_ann_row = PyTuple_GetItem(py_ann_rows, i);
475 if (!PyTuple_Check(py_ann_row)) {
476 srd_err("Protocol decoder %s annotation rows "
477 "must be tuples.", module_name);
480 if (PyTuple_Size(py_ann_row) != 3
481 || !PyUnicode_Check(PyTuple_GetItem(py_ann_row, 0))
482 || !PyUnicode_Check(PyTuple_GetItem(py_ann_row, 1))
483 || !PyTuple_Check(PyTuple_GetItem(py_ann_row, 2))) {
484 srd_err("Protocol decoder %s annotation rows "
485 "must contain tuples containing two "
486 "strings and a tuple.", module_name);
490 if (py_str_as_str(PyTuple_GetItem(py_ann_row, 0), &ann_row_id) != SRD_OK)
493 if (py_str_as_str(PyTuple_GetItem(py_ann_row, 1), &ann_row_desc) != SRD_OK)
496 py_ann_classes = PyTuple_GetItem(py_ann_row, 2);
498 for (j = 0; j < PyTuple_Size(py_ann_classes); j++) {
499 py_long = PyTuple_GetItem(py_ann_classes, j);
500 if (!PyLong_Check(py_long)) {
501 srd_err("Protocol decoder %s annotation row class "
502 "list must only contain numbers.", module_name);
505 ann_classes = g_slist_append(ann_classes,
506 GINT_TO_POINTER(PyLong_AsLong(py_long)));
509 ann_row = g_malloc0(sizeof(struct srd_decoder_annotation_row));
510 ann_row->id = ann_row_id;
511 ann_row->desc = ann_row_desc;
512 ann_row->ann_classes = ann_classes;
513 d->annotation_rows = g_slist_append(d->annotation_rows, ann_row);
517 /* Convert binary class to GSList of char *. */
519 if (PyObject_HasAttrString(d->py_dec, "binary")) {
520 py_bin_classes = PyObject_GetAttrString(d->py_dec, "binary");
521 if (!PyTuple_Check(py_bin_classes)) {
522 srd_err("Protocol decoder %s binary classes should "
523 "be a tuple.", module_name);
526 for (i = 0; i < PyTuple_Size(py_bin_classes); i++) {
527 py_bin_class = PyTuple_GetItem(py_bin_classes, i);
528 if (!PyTuple_Check(py_bin_class)) {
529 srd_err("Protocol decoder %s binary classes "
530 "should consist of tuples.", module_name);
533 if (PyTuple_Size(py_bin_class) != 2
534 || !PyUnicode_Check(PyTuple_GetItem(py_bin_class, 0))
535 || !PyUnicode_Check(PyTuple_GetItem(py_bin_class, 1))) {
536 srd_err("Protocol decoder %s binary classes should "
537 "contain tuples with two strings.", module_name);
541 if (py_strseq_to_char(py_bin_class, &bin) != SRD_OK) {
544 d->binary = g_slist_append(d->binary, bin);
548 /* Append it to the list of supported/loaded decoders. */
549 pd_list = g_slist_append(pd_list, d);
555 Py_XDECREF(py_method);
556 Py_XDECREF(py_basedec);
557 Py_XDECREF(d->py_dec);
558 Py_XDECREF(d->py_mod);
566 * Return a protocol decoder's docstring.
568 * @param dec The loaded protocol decoder.
570 * @return A newly allocated buffer containing the protocol decoder's
571 * documentation. The caller is responsible for free'ing the buffer.
575 SRD_API char *srd_decoder_doc_get(const struct srd_decoder *dec)
580 if (!srd_check_init())
586 if (!PyObject_HasAttrString(dec->py_mod, "__doc__"))
589 if (!(py_str = PyObject_GetAttrString(dec->py_mod, "__doc__"))) {
590 srd_exception_catch("Failed to get docstring");
595 if (py_str != Py_None)
596 py_str_as_str(py_str, &doc);
602 static void free_channels(GSList *channellist)
605 struct srd_channel *pdch;
607 if (channellist == NULL)
610 for (l = channellist; l; l = l->next) {
617 g_slist_free(channellist);
621 * Unload the specified protocol decoder.
623 * @param dec The struct srd_decoder to be unloaded.
625 * @return SRD_OK upon success, a (negative) error code otherwise.
629 SRD_API int srd_decoder_unload(struct srd_decoder *dec)
631 struct srd_decoder_option *o;
632 struct srd_session *sess;
635 if (!srd_check_init())
641 srd_dbg("Unloading protocol decoder '%s'.", dec->name);
644 * Since any instances of this decoder need to be released as well,
645 * but they could be anywhere in the stack, just free the entire
646 * stack. A frontend reloading a decoder thus has to restart all
647 * instances, and rebuild the stack.
649 for (l = sessions; l; l = l->next) {
651 srd_inst_free_all(sess, NULL);
654 for (l = dec->options; l; l = l->next) {
658 g_variant_unref(o->def);
661 g_slist_free(dec->options);
663 free_channels(dec->channels);
664 free_channels(dec->opt_channels);
667 g_free(dec->longname);
669 g_free(dec->license);
671 /* The module's Decoder class. */
672 Py_XDECREF(dec->py_dec);
673 /* The module itself. */
674 Py_XDECREF(dec->py_mod);
681 static void srd_decoder_load_all_zip_path(char *path)
683 PyObject *zipimport_mod, *zipimporter_class, *zipimporter;
684 PyObject *prefix_obj, *files, *key, *value, *set, *modname;
689 set = files = prefix_obj = zipimporter = zipimporter_class = NULL;
691 zipimport_mod = PyImport_ImportModule("zipimport");
692 if (zipimport_mod == NULL)
695 zipimporter_class = PyObject_GetAttrString(zipimport_mod, "zipimporter");
696 if (zipimporter_class == NULL)
699 zipimporter = PyObject_CallFunction(zipimporter_class, "s", path);
700 if (zipimporter == NULL)
703 prefix_obj = PyObject_GetAttrString(zipimporter, "prefix");
704 if (prefix_obj == NULL)
707 files = PyObject_GetAttrString(zipimporter, "_files");
711 set = PySet_New(NULL);
715 if (py_str_as_str(prefix_obj, &prefix) != SRD_OK)
718 prefix_len = strlen(prefix);
720 while (PyDict_Next(files, &pos, &key, &value)) {
722 if (py_str_as_str(key, &path) == SRD_OK) {
723 if (strlen(path) > prefix_len &&
724 !memcmp(path, prefix, prefix_len) &&
725 (slash = strchr(path+prefix_len, '/'))) {
727 PyUnicode_FromStringAndSize(path+prefix_len,
728 slash-(path+prefix_len));
729 if (modname == NULL) {
732 PySet_Add(set, modname);
742 while ((modname = PySet_Pop(set))) {
744 if (py_str_as_str(modname, &modname_str) == SRD_OK) {
745 /* The directory name is the module name (e.g. "i2c"). */
746 srd_decoder_load(modname_str);
755 Py_XDECREF(prefix_obj);
756 Py_XDECREF(zipimporter);
757 Py_XDECREF(zipimporter_class);
758 Py_XDECREF(zipimport_mod);
762 static void srd_decoder_load_all_path(char *path)
765 const gchar *direntry;
767 if (!(dir = g_dir_open(path, 0, NULL))) {
768 /* Not really fatal */
769 /* Try zipimport method too */
770 srd_decoder_load_all_zip_path(path);
774 /* This ignores errors returned by srd_decoder_load(). That
775 * function will have logged the cause, but in any case we
776 * want to continue anyway. */
777 while ((direntry = g_dir_read_name(dir)) != NULL) {
778 /* The directory name is the module name (e.g. "i2c"). */
779 srd_decoder_load(direntry);
786 * Load all installed protocol decoders.
788 * @return SRD_OK upon success, a (negative) error code otherwise.
792 SRD_API int srd_decoder_load_all(void)
796 if (!srd_check_init())
799 for (l = searchpaths; l; l = l->next)
800 srd_decoder_load_all_path(l->data);
806 * Unload all loaded protocol decoders.
808 * @return SRD_OK upon success, a (negative) error code otherwise.
812 SRD_API int srd_decoder_unload_all(void)
815 struct srd_decoder *dec;
817 for (l = pd_list; l; l = l->next) {
819 srd_decoder_unload(dec);
821 g_slist_free(pd_list);