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