]> sigrok.org Git - libsigrokdecode.git/blob - decoder.c
260f6367787597bc8f9c5818bf362f574b9b1c81
[libsigrokdecode.git] / decoder.c
1 /*
2  * This file is part of the libsigrokdecode 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 <config.h>
22 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include "libsigrokdecode.h"
24 #include <glib.h>
25
26 /**
27  * @file
28  *
29  * Listing, loading, unloading, and handling protocol decoders.
30  */
31
32 /**
33  * @defgroup grp_decoder Protocol decoders
34  *
35  * Handling protocol decoders.
36  *
37  * @{
38  */
39
40 /** @cond PRIVATE */
41
42 /* The list of loaded protocol decoders. */
43 static GSList *pd_list = NULL;
44
45 /* srd.c */
46 extern SRD_PRIV GSList *searchpaths;
47
48 /* session.c */
49 extern SRD_PRIV GSList *sessions;
50 extern SRD_PRIV int max_session_id;
51
52 /* module_sigrokdecode.c */
53 extern SRD_PRIV PyObject *mod_sigrokdecode;
54
55 /** @endcond */
56
57 static gboolean srd_check_init(void)
58 {
59         if (max_session_id < 0) {
60                 srd_err("Library is not initialized.");
61                 return FALSE;
62         } else
63                 return TRUE;
64 }
65
66 /**
67  * Returns the list of loaded protocol decoders.
68  *
69  * This is a GSList of pointers to struct srd_decoder items.
70  *
71  * @return List of decoders, NULL if none are supported or loaded.
72  *
73  * @since 0.2.0
74  */
75 SRD_API const GSList *srd_decoder_list(void)
76 {
77         return pd_list;
78 }
79
80 /**
81  * Get the decoder with the specified ID.
82  *
83  * @param id The ID string of the decoder to return.
84  *
85  * @return The decoder with the specified ID, or NULL if not found.
86  *
87  * @since 0.1.0
88  */
89 SRD_API struct srd_decoder *srd_decoder_get_by_id(const char *id)
90 {
91         GSList *l;
92         struct srd_decoder *dec;
93
94         for (l = pd_list; l; l = l->next) {
95                 dec = l->data;
96                 if (!strcmp(dec->id, id))
97                         return dec;
98         }
99
100         return NULL;
101 }
102
103 static void channel_free(void *data)
104 {
105         struct srd_channel *ch = data;
106
107         if (!ch)
108                 return;
109
110         g_free(ch->desc);
111         g_free(ch->name);
112         g_free(ch->id);
113         g_free(ch);
114 }
115
116 static void variant_free(void *data)
117 {
118         GVariant *var = data;
119
120         if (!var)
121                 return;
122
123         g_variant_unref(var);
124 }
125
126 static void annotation_row_free(void *data)
127 {
128         struct srd_decoder_annotation_row *row = data;
129
130         if (!row)
131                 return;
132
133         g_slist_free(row->ann_classes);
134         g_free(row->desc);
135         g_free(row->id);
136         g_free(row);
137 }
138
139 static void decoder_option_free(void *data)
140 {
141         struct srd_decoder_option *opt = data;
142
143         if (!opt)
144                 return;
145
146         g_slist_free_full(opt->values, &variant_free);
147         variant_free(opt->def);
148         g_free(opt->desc);
149         g_free(opt->id);
150         g_free(opt);
151 }
152
153 static void decoder_free(struct srd_decoder *dec)
154 {
155         PyGILState_STATE gstate;
156
157         if (!dec)
158                 return;
159
160         gstate = PyGILState_Ensure();
161         Py_XDECREF(dec->py_dec);
162         Py_XDECREF(dec->py_mod);
163         PyGILState_Release(gstate);
164
165         g_slist_free_full(dec->options, &decoder_option_free);
166         g_slist_free_full(dec->binary, (GDestroyNotify)&g_strfreev);
167         g_slist_free_full(dec->annotation_rows, &annotation_row_free);
168         g_slist_free_full(dec->annotations, (GDestroyNotify)&g_strfreev);
169         g_slist_free_full(dec->opt_channels, &channel_free);
170         g_slist_free_full(dec->channels, &channel_free);
171
172         g_slist_free_full(dec->outputs, g_free);
173         g_slist_free_full(dec->inputs, g_free);
174         g_free(dec->license);
175         g_free(dec->desc);
176         g_free(dec->longname);
177         g_free(dec->name);
178         g_free(dec->id);
179
180         g_free(dec);
181 }
182
183 static int get_channels(const struct srd_decoder *d, const char *attr,
184                 GSList **out_pdchl, int offset)
185 {
186         PyObject *py_channellist, *py_entry;
187         struct srd_channel *pdch;
188         GSList *pdchl;
189         ssize_t i;
190         PyGILState_STATE gstate;
191
192         gstate = PyGILState_Ensure();
193
194         if (!PyObject_HasAttrString(d->py_dec, attr)) {
195                 /* No channels of this type specified. */
196                 PyGILState_Release(gstate);
197                 return SRD_OK;
198         }
199
200         pdchl = NULL;
201
202         py_channellist = PyObject_GetAttrString(d->py_dec, attr);
203         if (!py_channellist)
204                 goto except_out;
205
206         if (!PyTuple_Check(py_channellist)) {
207                 srd_err("Protocol decoder %s %s attribute is not a tuple.",
208                         d->name, attr);
209                 goto err_out;
210         }
211
212         for (i = PyTuple_Size(py_channellist) - 1; i >= 0; i--) {
213                 py_entry = PyTuple_GetItem(py_channellist, i);
214                 if (!py_entry)
215                         goto except_out;
216
217                 if (!PyDict_Check(py_entry)) {
218                         srd_err("Protocol decoder %s %s attribute is not "
219                                 "a list of dict elements.", d->name, attr);
220                         goto err_out;
221                 }
222                 pdch = g_malloc(sizeof(struct srd_channel));
223                 /* Add to list right away so it doesn't get lost. */
224                 pdchl = g_slist_prepend(pdchl, pdch);
225
226                 if (py_dictitem_as_str(py_entry, "id", &pdch->id) != SRD_OK)
227                         goto err_out;
228                 if (py_dictitem_as_str(py_entry, "name", &pdch->name) != SRD_OK)
229                         goto err_out;
230                 if (py_dictitem_as_str(py_entry, "desc", &pdch->desc) != SRD_OK)
231                         goto err_out;
232
233                 pdch->order = offset + i;
234         }
235
236         Py_DECREF(py_channellist);
237         *out_pdchl = pdchl;
238
239         PyGILState_Release(gstate);
240
241         return SRD_OK;
242
243 except_out:
244         srd_exception_catch("Failed to get %s list of %s decoder",
245                         attr, d->name);
246
247 err_out:
248         g_slist_free_full(pdchl, &channel_free);
249         Py_XDECREF(py_channellist);
250         PyGILState_Release(gstate);
251
252         return SRD_ERR_PYTHON;
253 }
254
255 static int get_options(struct srd_decoder *d)
256 {
257         PyObject *py_opts, *py_opt, *py_str, *py_values, *py_default, *py_item;
258         GSList *options;
259         struct srd_decoder_option *o;
260         GVariant *gvar;
261         ssize_t opt, i;
262         PyGILState_STATE gstate;
263
264         gstate = PyGILState_Ensure();
265
266         if (!PyObject_HasAttrString(d->py_dec, "options")) {
267                 /* No options, that's fine. */
268                 PyGILState_Release(gstate);
269                 return SRD_OK;
270         }
271
272         options = NULL;
273
274         /* If present, options must be a tuple. */
275         py_opts = PyObject_GetAttrString(d->py_dec, "options");
276         if (!py_opts)
277                 goto except_out;
278
279         if (!PyTuple_Check(py_opts)) {
280                 srd_err("Protocol decoder %s: options attribute is not "
281                                 "a tuple.", d->id);
282                 goto err_out;
283         }
284
285         for (opt = PyTuple_Size(py_opts) - 1; opt >= 0; opt--) {
286                 py_opt = PyTuple_GetItem(py_opts, opt);
287                 if (!py_opt)
288                         goto except_out;
289
290                 if (!PyDict_Check(py_opt)) {
291                         srd_err("Protocol decoder %s options: each option "
292                                         "must consist of a dictionary.", d->name);
293                         goto err_out;
294                 }
295
296                 o = g_malloc0(sizeof(struct srd_decoder_option));
297                 /* Add to list right away so it doesn't get lost. */
298                 options = g_slist_prepend(options, o);
299
300                 py_str = PyDict_GetItemString(py_opt, "id");
301                 if (!py_str) {
302                         srd_err("Protocol decoder %s option %zd has no ID.",
303                                 d->name, opt);
304                         goto err_out;
305                 }
306                 if (py_str_as_str(py_str, &o->id) != SRD_OK)
307                         goto err_out;
308
309                 py_str = PyDict_GetItemString(py_opt, "desc");
310                 if (py_str) {
311                         if (py_str_as_str(py_str, &o->desc) != SRD_OK)
312                                 goto err_out;
313                 }
314
315                 py_default = PyDict_GetItemString(py_opt, "default");
316                 if (py_default) {
317                         gvar = py_obj_to_variant(py_default);
318                         if (!gvar) {
319                                 srd_err("Protocol decoder %s option 'default' has "
320                                         "invalid default value.", d->name);
321                                 goto err_out;
322                         }
323                         o->def = g_variant_ref_sink(gvar);
324                 }
325
326                 py_values = PyDict_GetItemString(py_opt, "values");
327                 if (py_values) {
328                         /*
329                          * A default is required if a list of values is
330                          * given, since it's used to verify their type.
331                          */
332                         if (!o->def) {
333                                 srd_err("No default for option '%s'.", o->id);
334                                 goto err_out;
335                         }
336                         if (!PyTuple_Check(py_values)) {
337                                 srd_err("Option '%s' values should be a tuple.", o->id);
338                                 goto err_out;
339                         }
340
341                         for (i = PyTuple_Size(py_values) - 1; i >= 0; i--) {
342                                 py_item = PyTuple_GetItem(py_values, i);
343                                 if (!py_item)
344                                         goto except_out;
345
346                                 if (py_default && (Py_TYPE(py_default) != Py_TYPE(py_item))) {
347                                         srd_err("All values for option '%s' must be "
348                                                 "of the same type as the default.",
349                                                 o->id);
350                                         goto err_out;
351                                 }
352                                 gvar = py_obj_to_variant(py_item);
353                                 if (!gvar) {
354                                         srd_err("Protocol decoder %s option 'values' "
355                                                 "contains invalid value.", d->name);
356                                         goto err_out;
357                                 }
358                                 o->values = g_slist_prepend(o->values,
359                                                 g_variant_ref_sink(gvar));
360                         }
361                 }
362         }
363         d->options = options;
364         Py_DECREF(py_opts);
365         PyGILState_Release(gstate);
366
367         return SRD_OK;
368
369 except_out:
370         srd_exception_catch("Failed to get %s decoder options", d->name);
371
372 err_out:
373         g_slist_free_full(options, &decoder_option_free);
374         Py_XDECREF(py_opts);
375         PyGILState_Release(gstate);
376
377         return SRD_ERR_PYTHON;
378 }
379
380 /* Convert annotation class attribute to GSList of char **. */
381 static int get_annotations(struct srd_decoder *dec)
382 {
383         PyObject *py_annlist, *py_ann;
384         GSList *annotations;
385         char **annpair;
386         ssize_t i;
387         PyGILState_STATE gstate;
388
389         gstate = PyGILState_Ensure();
390
391         if (!PyObject_HasAttrString(dec->py_dec, "annotations")) {
392                 PyGILState_Release(gstate);
393                 return SRD_OK;
394         }
395
396         annotations = NULL;
397
398         py_annlist = PyObject_GetAttrString(dec->py_dec, "annotations");
399         if (!py_annlist)
400                 goto except_out;
401
402         if (!PyTuple_Check(py_annlist)) {
403                 srd_err("Protocol decoder %s annotations should "
404                         "be a tuple.", dec->name);
405                 goto err_out;
406         }
407
408         for (i = PyTuple_Size(py_annlist) - 1; i >= 0; i--) {
409                 py_ann = PyTuple_GetItem(py_annlist, i);
410                 if (!py_ann)
411                         goto except_out;
412
413                 if (!PyTuple_Check(py_ann) || PyTuple_Size(py_ann) != 2) {
414                         srd_err("Protocol decoder %s annotation %zd should "
415                                 "be a tuple with two elements.",
416                                 dec->name, i + 1);
417                         goto err_out;
418                 }
419                 if (py_strseq_to_char(py_ann, &annpair) != SRD_OK)
420                         goto err_out;
421
422                 annotations = g_slist_prepend(annotations, annpair);
423         }
424         dec->annotations = annotations;
425         Py_DECREF(py_annlist);
426         PyGILState_Release(gstate);
427
428         return SRD_OK;
429
430 except_out:
431         srd_exception_catch("Failed to get %s decoder annotations", dec->name);
432
433 err_out:
434         g_slist_free_full(annotations, (GDestroyNotify)&g_strfreev);
435         Py_XDECREF(py_annlist);
436         PyGILState_Release(gstate);
437
438         return SRD_ERR_PYTHON;
439 }
440
441 /* Convert annotation_rows to GSList of 'struct srd_decoder_annotation_row'. */
442 static int get_annotation_rows(struct srd_decoder *dec)
443 {
444         PyObject *py_ann_rows, *py_ann_row, *py_ann_classes, *py_item;
445         GSList *annotation_rows;
446         struct srd_decoder_annotation_row *ann_row;
447         ssize_t i, k;
448         size_t class_idx;
449         PyGILState_STATE gstate;
450
451         gstate = PyGILState_Ensure();
452
453         if (!PyObject_HasAttrString(dec->py_dec, "annotation_rows")) {
454                 PyGILState_Release(gstate);
455                 return SRD_OK;
456         }
457
458         annotation_rows = NULL;
459
460         py_ann_rows = PyObject_GetAttrString(dec->py_dec, "annotation_rows");
461         if (!py_ann_rows)
462                 goto except_out;
463
464         if (!PyTuple_Check(py_ann_rows)) {
465                 srd_err("Protocol decoder %s annotation_rows "
466                         "must be a tuple.", dec->name);
467                 goto err_out;
468         }
469
470         for (i = PyTuple_Size(py_ann_rows) - 1; i >= 0; i--) {
471                 py_ann_row = PyTuple_GetItem(py_ann_rows, i);
472                 if (!py_ann_row)
473                         goto except_out;
474
475                 if (!PyTuple_Check(py_ann_row) || PyTuple_Size(py_ann_row) != 3) {
476                         srd_err("Protocol decoder %s annotation_rows "
477                                 "must contain only tuples of 3 elements.",
478                                 dec->name);
479                         goto err_out;
480                 }
481                 ann_row = g_malloc0(sizeof(struct srd_decoder_annotation_row));
482                 /* Add to list right away so it doesn't get lost. */
483                 annotation_rows = g_slist_prepend(annotation_rows, ann_row);
484
485                 py_item = PyTuple_GetItem(py_ann_row, 0);
486                 if (!py_item)
487                         goto except_out;
488                 if (py_str_as_str(py_item, &ann_row->id) != SRD_OK)
489                         goto err_out;
490
491                 py_item = PyTuple_GetItem(py_ann_row, 1);
492                 if (!py_item)
493                         goto except_out;
494                 if (py_str_as_str(py_item, &ann_row->desc) != SRD_OK)
495                         goto err_out;
496
497                 py_ann_classes = PyTuple_GetItem(py_ann_row, 2);
498                 if (!py_ann_classes)
499                         goto except_out;
500
501                 if (!PyTuple_Check(py_ann_classes)) {
502                         srd_err("Protocol decoder %s annotation_rows tuples "
503                                 "must have a tuple of numbers as 3rd element.",
504                                 dec->name);
505                         goto err_out;
506                 }
507
508                 for (k = PyTuple_Size(py_ann_classes) - 1; k >= 0; k--) {
509                         py_item = PyTuple_GetItem(py_ann_classes, k);
510                         if (!py_item)
511                                 goto except_out;
512
513                         if (!PyLong_Check(py_item)) {
514                                 srd_err("Protocol decoder %s annotation row "
515                                         "class tuple must only contain numbers.",
516                                         dec->name);
517                                 goto err_out;
518                         }
519                         class_idx = PyLong_AsSize_t(py_item);
520                         if (PyErr_Occurred())
521                                 goto except_out;
522
523                         ann_row->ann_classes = g_slist_prepend(ann_row->ann_classes,
524                                         GSIZE_TO_POINTER(class_idx));
525                 }
526         }
527         dec->annotation_rows = annotation_rows;
528         Py_DECREF(py_ann_rows);
529         PyGILState_Release(gstate);
530
531         return SRD_OK;
532
533 except_out:
534         srd_exception_catch("Failed to get %s decoder annotation rows",
535                         dec->name);
536
537 err_out:
538         g_slist_free_full(annotation_rows, &annotation_row_free);
539         Py_XDECREF(py_ann_rows);
540         PyGILState_Release(gstate);
541
542         return SRD_ERR_PYTHON;
543 }
544
545 /* Convert binary classes to GSList of char **. */
546 static int get_binary_classes(struct srd_decoder *dec)
547 {
548         PyObject *py_bin_classes, *py_bin_class;
549         GSList *bin_classes;
550         char **bin;
551         ssize_t i;
552         PyGILState_STATE gstate;
553
554         gstate = PyGILState_Ensure();
555
556         if (!PyObject_HasAttrString(dec->py_dec, "binary")) {
557                 PyGILState_Release(gstate);
558                 return SRD_OK;
559         }
560
561         bin_classes = NULL;
562
563         py_bin_classes = PyObject_GetAttrString(dec->py_dec, "binary");
564         if (!py_bin_classes)
565                 goto except_out;
566
567         if (!PyTuple_Check(py_bin_classes)) {
568                 srd_err("Protocol decoder %s binary classes should "
569                         "be a tuple.", dec->name);
570                 goto err_out;
571         }
572
573         for (i = PyTuple_Size(py_bin_classes) - 1; i >= 0; i--) {
574                 py_bin_class = PyTuple_GetItem(py_bin_classes, i);
575                 if (!py_bin_class)
576                         goto except_out;
577
578                 if (!PyTuple_Check(py_bin_class)
579                                 || PyTuple_Size(py_bin_class) != 2) {
580                         srd_err("Protocol decoder %s binary classes should "
581                                 "consist only of tuples of 2 elements.",
582                                 dec->name);
583                         goto err_out;
584                 }
585                 if (py_strseq_to_char(py_bin_class, &bin) != SRD_OK)
586                         goto err_out;
587
588                 bin_classes = g_slist_prepend(bin_classes, bin);
589         }
590         dec->binary = bin_classes;
591         Py_DECREF(py_bin_classes);
592         PyGILState_Release(gstate);
593
594         return SRD_OK;
595
596 except_out:
597         srd_exception_catch("Failed to get %s decoder binary classes",
598                         dec->name);
599
600 err_out:
601         g_slist_free_full(bin_classes, (GDestroyNotify)&g_strfreev);
602         Py_XDECREF(py_bin_classes);
603         PyGILState_Release(gstate);
604
605         return SRD_ERR_PYTHON;
606 }
607
608 /* Check whether the Decoder class defines the named method. */
609 static int check_method(PyObject *py_dec, const char *mod_name,
610                 const char *method_name)
611 {
612         PyObject *py_method;
613         int is_callable;
614         PyGILState_STATE gstate;
615
616         gstate = PyGILState_Ensure();
617
618         py_method = PyObject_GetAttrString(py_dec, method_name);
619         if (!py_method) {
620                 srd_exception_catch("Protocol decoder %s Decoder class "
621                                 "has no %s() method", mod_name, method_name);
622                 PyGILState_Release(gstate);
623                 return SRD_ERR_PYTHON;
624         }
625
626         is_callable = PyCallable_Check(py_method);
627         Py_DECREF(py_method);
628
629         PyGILState_Release(gstate);
630
631         if (!is_callable) {
632                 srd_err("Protocol decoder %s Decoder class attribute '%s' "
633                         "is not a method.", mod_name, method_name);
634                 return SRD_ERR_PYTHON;
635         }
636
637         return SRD_OK;
638 }
639
640 /**
641  * Get the API version of the specified decoder.
642  *
643  * @param d The decoder to use. Must not be NULL.
644  *
645  * @return The API version of the decoder, or 0 upon errors.
646  *
647  * @private
648  */
649 SRD_PRIV long srd_decoder_apiver(const struct srd_decoder *d)
650 {
651         PyObject *py_apiver;
652         long apiver;
653         PyGILState_STATE gstate;
654
655         if (!d)
656                 return 0;
657
658         gstate = PyGILState_Ensure();
659
660         py_apiver = PyObject_GetAttrString(d->py_dec, "api_version");
661         apiver = (py_apiver && PyLong_Check(py_apiver))
662                         ? PyLong_AsLong(py_apiver) : 0;
663         Py_XDECREF(py_apiver);
664
665         PyGILState_Release(gstate);
666
667         return apiver;
668 }
669
670 /**
671  * Load a protocol decoder module into the embedded Python interpreter.
672  *
673  * @param module_name The module name to be loaded.
674  *
675  * @return SRD_OK upon success, a (negative) error code otherwise.
676  *
677  * @since 0.1.0
678  */
679 SRD_API int srd_decoder_load(const char *module_name)
680 {
681         PyObject *py_basedec;
682         struct srd_decoder *d;
683         long apiver;
684         int is_subclass;
685         const char *fail_txt;
686         PyGILState_STATE gstate;
687
688         if (!srd_check_init())
689                 return SRD_ERR;
690
691         if (!module_name)
692                 return SRD_ERR_ARG;
693
694         gstate = PyGILState_Ensure();
695
696         if (PyDict_GetItemString(PyImport_GetModuleDict(), module_name)) {
697                 /* Module was already imported. */
698                 PyGILState_Release(gstate);
699                 return SRD_OK;
700         }
701
702         d = g_malloc0(sizeof(struct srd_decoder));
703         fail_txt = NULL;
704
705         d->py_mod = py_import_by_name(module_name);
706         if (!d->py_mod) {
707                 fail_txt = "import by name failed";
708                 goto except_out;
709         }
710
711         if (!mod_sigrokdecode) {
712                 srd_err("sigrokdecode module not loaded.");
713                 fail_txt = "sigrokdecode(3) not loaded";
714                 goto err_out;
715         }
716
717         /* Get the 'Decoder' class as Python object. */
718         d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder");
719         if (!d->py_dec) {
720                 fail_txt = "no 'Decoder' attribute in imported module";
721                 goto except_out;
722         }
723
724         py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder");
725         if (!py_basedec) {
726                 fail_txt = "no 'Decoder' attribute in sigrokdecode(3)";
727                 goto except_out;
728         }
729
730         is_subclass = PyObject_IsSubclass(d->py_dec, py_basedec);
731         Py_DECREF(py_basedec);
732
733         if (!is_subclass) {
734                 srd_err("Decoder class in protocol decoder module %s is not "
735                         "a subclass of sigrokdecode.Decoder.", module_name);
736                 fail_txt = "not a subclass of sigrokdecode.Decoder";
737                 goto err_out;
738         }
739
740         /*
741          * Check that this decoder has the correct PD API version.
742          * PDs of different API versions are incompatible and cannot work.
743          */
744         apiver = srd_decoder_apiver(d);
745         if (apiver != 3) {
746                 srd_exception_catch("Only PD API version 3 is supported, "
747                         "decoder %s has version %ld", module_name, apiver);
748                 fail_txt = "API version mismatch";
749                 goto err_out;
750         }
751
752         /* Check Decoder class for required methods. */
753
754         if (check_method(d->py_dec, module_name, "start") != SRD_OK) {
755                 fail_txt = "no 'start()' method";
756                 goto err_out;
757         }
758
759         if (check_method(d->py_dec, module_name, "decode") != SRD_OK) {
760                 fail_txt = "no 'decode()' method";
761                 goto err_out;
762         }
763
764         /* Store required fields in newly allocated strings. */
765         if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK) {
766                 fail_txt = "no 'id' attribute";
767                 goto err_out;
768         }
769
770         if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK) {
771                 fail_txt = "no 'name' attribute";
772                 goto err_out;
773         }
774
775         if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK) {
776                 fail_txt = "no 'longname' attribute";
777                 goto err_out;
778         }
779
780         if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK) {
781                 fail_txt = "no 'desc' attribute";
782                 goto err_out;
783         }
784
785         if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK) {
786                 fail_txt = "no 'license' attribute";
787                 goto err_out;
788         }
789
790         if (py_attr_as_strlist(d->py_dec, "inputs", &(d->inputs)) != SRD_OK) {
791                 fail_txt = "missing or malformed 'inputs' attribute";
792                 goto err_out;
793         }
794
795         if (py_attr_as_strlist(d->py_dec, "outputs", &(d->outputs)) != SRD_OK) {
796                 fail_txt = "missing or malformed 'outputs' attribute";
797                 goto err_out;
798         }
799
800         /* All options and their default values. */
801         if (get_options(d) != SRD_OK) {
802                 fail_txt = "cannot get options";
803                 goto err_out;
804         }
805
806         /* Check and import required channels. */
807         if (get_channels(d, "channels", &d->channels, 0) != SRD_OK) {
808                 fail_txt = "cannot get channels";
809                 goto err_out;
810         }
811
812         /* Check and import optional channels. */
813         if (get_channels(d, "optional_channels", &d->opt_channels,
814                                 g_slist_length(d->channels)) != SRD_OK) {
815                 fail_txt = "cannot get optional channels";
816                 goto err_out;
817         }
818
819         if (get_annotations(d) != SRD_OK) {
820                 fail_txt = "cannot get annotations";
821                 goto err_out;
822         }
823
824         if (get_annotation_rows(d) != SRD_OK) {
825                 fail_txt = "cannot get annotation rows";
826                 goto err_out;
827         }
828
829         if (get_binary_classes(d) != SRD_OK) {
830                 fail_txt = "cannot get binary classes";
831                 goto err_out;
832         }
833
834         PyGILState_Release(gstate);
835
836         /* Append it to the list of loaded decoders. */
837         pd_list = g_slist_append(pd_list, d);
838
839         return SRD_OK;
840
841 except_out:
842         /* Don't show a message for the "common" directory, it's not a PD. */
843         if (strcmp(module_name, "common")) {
844                 srd_exception_catch("Failed to load decoder %s: %s",
845                                     module_name, fail_txt);
846         }
847         fail_txt = NULL;
848
849 err_out:
850         if (fail_txt)
851                 srd_err("Failed to load decoder %s: %s", module_name, fail_txt);
852         decoder_free(d);
853         PyGILState_Release(gstate);
854
855         return SRD_ERR_PYTHON;
856 }
857
858 /**
859  * Return a protocol decoder's docstring.
860  *
861  * @param dec The loaded protocol decoder.
862  *
863  * @return A newly allocated buffer containing the protocol decoder's
864  *         documentation. The caller is responsible for free'ing the buffer.
865  *
866  * @since 0.1.0
867  */
868 SRD_API char *srd_decoder_doc_get(const struct srd_decoder *dec)
869 {
870         PyObject *py_str;
871         char *doc;
872         PyGILState_STATE gstate;
873
874         if (!srd_check_init())
875                 return NULL;
876
877         if (!dec)
878                 return NULL;
879
880         gstate = PyGILState_Ensure();
881
882         if (!PyObject_HasAttrString(dec->py_mod, "__doc__"))
883                 goto err;
884
885         if (!(py_str = PyObject_GetAttrString(dec->py_mod, "__doc__"))) {
886                 srd_exception_catch("Failed to get docstring");
887                 goto err;
888         }
889
890         doc = NULL;
891         if (py_str != Py_None)
892                 py_str_as_str(py_str, &doc);
893         Py_DECREF(py_str);
894
895         PyGILState_Release(gstate);
896
897         return doc;
898
899 err:
900         PyGILState_Release(gstate);
901
902         return NULL;
903 }
904
905 /**
906  * Unload the specified protocol decoder.
907  *
908  * @param dec The struct srd_decoder to be unloaded.
909  *
910  * @return SRD_OK upon success, a (negative) error code otherwise.
911  *
912  * @since 0.1.0
913  */
914 SRD_API int srd_decoder_unload(struct srd_decoder *dec)
915 {
916         struct srd_session *sess;
917         GSList *l;
918
919         if (!srd_check_init())
920                 return SRD_ERR;
921
922         if (!dec)
923                 return SRD_ERR_ARG;
924
925         /*
926          * Since any instances of this decoder need to be released as well,
927          * but they could be anywhere in the stack, just free the entire
928          * stack. A frontend reloading a decoder thus has to restart all
929          * instances, and rebuild the stack.
930          */
931         for (l = sessions; l; l = l->next) {
932                 sess = l->data;
933                 srd_inst_free_all(sess);
934         }
935
936         /* Remove the PD from the list of loaded decoders. */
937         pd_list = g_slist_remove(pd_list, dec);
938
939         decoder_free(dec);
940
941         return SRD_OK;
942 }
943
944 static void srd_decoder_load_all_zip_path(char *zip_path)
945 {
946         PyObject *zipimport_mod, *zipimporter_class, *zipimporter;
947         PyObject *prefix_obj, *files, *key, *value, *set, *modname;
948         Py_ssize_t pos = 0;
949         char *prefix;
950         size_t prefix_len;
951         PyGILState_STATE gstate;
952
953         set = files = prefix_obj = zipimporter = zipimporter_class = NULL;
954
955         gstate = PyGILState_Ensure();
956
957         zipimport_mod = py_import_by_name("zipimport");
958         if (zipimport_mod == NULL)
959                 goto err_out;
960
961         zipimporter_class = PyObject_GetAttrString(zipimport_mod, "zipimporter");
962         if (zipimporter_class == NULL)
963                 goto err_out;
964
965         zipimporter = PyObject_CallFunction(zipimporter_class, "s", zip_path);
966         if (zipimporter == NULL)
967                 goto err_out;
968
969         prefix_obj = PyObject_GetAttrString(zipimporter, "prefix");
970         if (prefix_obj == NULL)
971                 goto err_out;
972
973         files = PyObject_GetAttrString(zipimporter, "_files");
974         if (files == NULL || !PyDict_Check(files))
975                 goto err_out;
976
977         set = PySet_New(NULL);
978         if (set == NULL)
979                 goto err_out;
980
981         if (py_str_as_str(prefix_obj, &prefix) != SRD_OK)
982                 goto err_out;
983
984         prefix_len = strlen(prefix);
985
986         while (PyDict_Next(files, &pos, &key, &value)) {
987                 char *path, *slash;
988                 if (py_str_as_str(key, &path) == SRD_OK) {
989                         if (strlen(path) > prefix_len
990                                         && memcmp(path, prefix, prefix_len) == 0
991                                         && (slash = strchr(path + prefix_len, '/'))) {
992
993                                 modname = PyUnicode_FromStringAndSize(path + prefix_len,
994                                                         slash - (path + prefix_len));
995                                 if (modname == NULL) {
996                                         PyErr_Clear();
997                                 } else {
998                                         PySet_Add(set, modname);
999                                         Py_DECREF(modname);
1000                                 }
1001                         }
1002                         g_free(path);
1003                 }
1004         }
1005         g_free(prefix);
1006
1007         while ((modname = PySet_Pop(set))) {
1008                 char *modname_str;
1009                 if (py_str_as_str(modname, &modname_str) == SRD_OK) {
1010                         /* The directory name is the module name (e.g. "i2c"). */
1011                         srd_decoder_load(modname_str);
1012                         g_free(modname_str);
1013                 }
1014                 Py_DECREF(modname);
1015         }
1016
1017 err_out:
1018         Py_XDECREF(set);
1019         Py_XDECREF(files);
1020         Py_XDECREF(prefix_obj);
1021         Py_XDECREF(zipimporter);
1022         Py_XDECREF(zipimporter_class);
1023         Py_XDECREF(zipimport_mod);
1024         PyErr_Clear();
1025         PyGILState_Release(gstate);
1026 }
1027
1028 static void srd_decoder_load_all_path(char *path)
1029 {
1030         GDir *dir;
1031         const gchar *direntry;
1032
1033         if (!(dir = g_dir_open(path, 0, NULL))) {
1034                 /* Not really fatal. Try zipimport method too. */
1035                 srd_decoder_load_all_zip_path(path);
1036                 return;
1037         }
1038
1039         /*
1040          * This ignores errors returned by srd_decoder_load(). That
1041          * function will have logged the cause, but in any case we
1042          * want to continue anyway.
1043          */
1044         while ((direntry = g_dir_read_name(dir)) != NULL) {
1045                 /* The directory name is the module name (e.g. "i2c"). */
1046                 srd_decoder_load(direntry);
1047         }
1048         g_dir_close(dir);
1049 }
1050
1051 /**
1052  * Load all installed protocol decoders.
1053  *
1054  * @return SRD_OK upon success, a (negative) error code otherwise.
1055  *
1056  * @since 0.1.0
1057  */
1058 SRD_API int srd_decoder_load_all(void)
1059 {
1060         GSList *l;
1061
1062         if (!srd_check_init())
1063                 return SRD_ERR;
1064
1065         for (l = searchpaths; l; l = l->next)
1066                 srd_decoder_load_all_path(l->data);
1067
1068         return SRD_OK;
1069 }
1070
1071 static void srd_decoder_unload_cb(void *arg, void *ignored)
1072 {
1073         (void)ignored;
1074
1075         srd_decoder_unload((struct srd_decoder *)arg);
1076 }
1077
1078 /**
1079  * Unload all loaded protocol decoders.
1080  *
1081  * @return SRD_OK upon success, a (negative) error code otherwise.
1082  *
1083  * @since 0.1.0
1084  */
1085 SRD_API int srd_decoder_unload_all(void)
1086 {
1087         g_slist_foreach(pd_list, srd_decoder_unload_cb, NULL);
1088         g_slist_free(pd_list);
1089         pd_list = NULL;
1090
1091         return SRD_OK;
1092 }
1093
1094 /** @} */