]> sigrok.org Git - libsigrokdecode.git/blob - decoder.c
d7395a679eb3d0bac8d9d91a2073cadd4490a1f9
[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  * @private
599  */
600 SRD_PRIV long srd_decoder_apiver(const struct srd_decoder *d)
601 {
602         PyObject *py_apiver;
603         long apiver;
604
605         if (!d)
606                 return 0;
607
608         py_apiver = PyObject_GetAttrString(d->py_dec, "api_version");
609         apiver = (py_apiver && PyLong_Check(py_apiver))
610                         ? PyLong_AsLong(py_apiver) : 0;
611         Py_XDECREF(py_apiver);
612
613         return apiver;
614 }
615
616 /**
617  * Load a protocol decoder module into the embedded Python interpreter.
618  *
619  * @param module_name The module name to be loaded.
620  *
621  * @return SRD_OK upon success, a (negative) error code otherwise.
622  *
623  * @since 0.1.0
624  */
625 SRD_API int srd_decoder_load(const char *module_name)
626 {
627         PyObject *py_basedec;
628         struct srd_decoder *d;
629         long apiver;
630         int is_subclass;
631         const char *fail_txt;
632
633         if (!srd_check_init())
634                 return SRD_ERR;
635
636         if (!module_name)
637                 return SRD_ERR_ARG;
638
639         if (PyDict_GetItemString(PyImport_GetModuleDict(), module_name)) {
640                 /* Module was already imported. */
641                 return SRD_OK;
642         }
643
644         srd_dbg("Loading protocol decoder '%s'.", module_name);
645
646         d = g_malloc0(sizeof(struct srd_decoder));
647         fail_txt = NULL;
648
649         d->py_mod = py_import_by_name(module_name);
650         if (!d->py_mod) {
651                 fail_txt = "import by name failed";
652                 goto except_out;
653         }
654
655         if (!mod_sigrokdecode) {
656                 srd_err("sigrokdecode module not loaded.");
657                 fail_txt = "sigrokdecode(3) not loaded";
658                 goto err_out;
659         }
660
661         /* Get the 'Decoder' class as Python object. */
662         d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder");
663         if (!d->py_dec) {
664                 fail_txt = "no 'Decoder' attribute in imported module";
665                 goto except_out;
666         }
667
668         py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder");
669         if (!py_basedec) {
670                 fail_txt = "no 'Decoder' attribute in sigrokdecode(3)";
671                 goto except_out;
672         }
673
674         is_subclass = PyObject_IsSubclass(d->py_dec, py_basedec);
675         Py_DECREF(py_basedec);
676
677         if (!is_subclass) {
678                 srd_err("Decoder class in protocol decoder module %s is not "
679                         "a subclass of sigrokdecode.Decoder.", module_name);
680                 fail_txt = "not a subclass of sigrokdecode.Decoder";
681                 goto err_out;
682         }
683
684         /*
685          * Check that this decoder has the correct PD API version.
686          * PDs of different API versions are incompatible and cannot work.
687          */
688         apiver = srd_decoder_apiver(d);
689         if (apiver != 3) {
690                 srd_exception_catch("Only PD API version 3 is supported, "
691                         "decoder %s has version %ld", module_name, apiver);
692                 fail_txt = "API version mismatch";
693                 goto err_out;
694         }
695
696         /* Check Decoder class for required methods.
697          */
698         if (check_method(d->py_dec, module_name, "start") != SRD_OK) {
699                 fail_txt = "no 'start()' method";
700                 goto err_out;
701         }
702
703         if (check_method(d->py_dec, module_name, "decode") != SRD_OK) {
704                 fail_txt = "no 'decode()' method";
705                 goto err_out;
706         }
707
708         /* Store required fields in newly allocated strings. */
709         if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK) {
710                 fail_txt = "no 'id' attribute";
711                 goto err_out;
712         }
713
714         if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK) {
715                 fail_txt = "no 'name' attribute";
716                 goto err_out;
717         }
718
719         if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK) {
720                 fail_txt = "no 'longname' attribute";
721                 goto err_out;
722         }
723
724         if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK) {
725                 fail_txt = "no 'desc' attribute";
726                 goto err_out;
727         }
728
729         if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK) {
730                 fail_txt = "no 'license' attribute";
731                 goto err_out;
732         }
733
734         if (py_attr_as_strlist(d->py_dec, "inputs", &(d->inputs)) != SRD_OK) {
735                 fail_txt = "missing or malformed 'inputs' attribute";
736                 goto err_out;
737         }
738
739         if (py_attr_as_strlist(d->py_dec, "outputs", &(d->outputs)) != SRD_OK) {
740                 fail_txt = "missing or malformed 'outputs' attribute";
741                 goto err_out;
742         }
743
744         /* All options and their default values. */
745         if (get_options(d) != SRD_OK) {
746                 fail_txt = "cannot get options";
747                 goto err_out;
748         }
749
750         /* Check and import required channels. */
751         if (get_channels(d, "channels", &d->channels, 0) != SRD_OK) {
752                 fail_txt = "cannot get channels";
753                 goto err_out;
754         }
755
756         /* Check and import optional channels. */
757         if (get_channels(d, "optional_channels", &d->opt_channels,
758                                 g_slist_length(d->channels)) != SRD_OK) {
759                 fail_txt = "cannot get optional channels";
760                 goto err_out;
761         }
762
763         if (get_annotations(d) != SRD_OK) {
764                 fail_txt = "cannot get annotations";
765                 goto err_out;
766         }
767
768         if (get_annotation_rows(d) != SRD_OK) {
769                 fail_txt = "cannot get annotation rows";
770                 goto err_out;
771         }
772
773         if (get_binary_classes(d) != SRD_OK) {
774                 fail_txt = "cannot get binary classes";
775                 goto err_out;
776         }
777
778         /* Append it to the list of loaded decoders. */
779         pd_list = g_slist_append(pd_list, d);
780
781         return SRD_OK;
782
783 except_out:
784         /* Don't show a message for the "common" directory, it's not a PD. */
785         if (strcmp(module_name, "common")) {
786                 srd_exception_catch("Failed to load decoder %s: %s",
787                                     module_name, fail_txt);
788         }
789         fail_txt = NULL;
790 err_out:
791         if (fail_txt)
792                 srd_err("Failed to load decoder %s: %s", module_name, fail_txt);
793         decoder_free(d);
794
795         return SRD_ERR_PYTHON;
796 }
797
798 /**
799  * Return a protocol decoder's docstring.
800  *
801  * @param dec The loaded protocol decoder.
802  *
803  * @return A newly allocated buffer containing the protocol decoder's
804  *         documentation. The caller is responsible for free'ing the buffer.
805  *
806  * @since 0.1.0
807  */
808 SRD_API char *srd_decoder_doc_get(const struct srd_decoder *dec)
809 {
810         PyObject *py_str;
811         char *doc;
812
813         if (!srd_check_init())
814                 return NULL;
815
816         if (!dec)
817                 return NULL;
818
819         if (!PyObject_HasAttrString(dec->py_mod, "__doc__"))
820                 return NULL;
821
822         if (!(py_str = PyObject_GetAttrString(dec->py_mod, "__doc__"))) {
823                 srd_exception_catch("Failed to get docstring");
824                 return NULL;
825         }
826
827         doc = NULL;
828         if (py_str != Py_None)
829                 py_str_as_str(py_str, &doc);
830         Py_DECREF(py_str);
831
832         return doc;
833 }
834
835 /**
836  * Unload the specified protocol decoder.
837  *
838  * @param dec The struct srd_decoder to be unloaded.
839  *
840  * @return SRD_OK upon success, a (negative) error code otherwise.
841  *
842  * @since 0.1.0
843  */
844 SRD_API int srd_decoder_unload(struct srd_decoder *dec)
845 {
846         struct srd_session *sess;
847         GSList *l;
848
849         if (!srd_check_init())
850                 return SRD_ERR;
851
852         if (!dec)
853                 return SRD_ERR_ARG;
854
855         srd_dbg("Unloading protocol decoder '%s'.", dec->name);
856
857         /*
858          * Since any instances of this decoder need to be released as well,
859          * but they could be anywhere in the stack, just free the entire
860          * stack. A frontend reloading a decoder thus has to restart all
861          * instances, and rebuild the stack.
862          */
863         for (l = sessions; l; l = l->next) {
864                 sess = l->data;
865                 srd_inst_free_all(sess);
866         }
867
868         /* Remove the PD from the list of loaded decoders. */
869         pd_list = g_slist_remove(pd_list, dec);
870
871         decoder_free(dec);
872
873         return SRD_OK;
874 }
875
876 static void srd_decoder_load_all_zip_path(char *path)
877 {
878         PyObject *zipimport_mod, *zipimporter_class, *zipimporter;
879         PyObject *prefix_obj, *files, *key, *value, *set, *modname;
880         Py_ssize_t pos = 0;
881         char *prefix;
882         size_t prefix_len;
883
884         set = files = prefix_obj = zipimporter = zipimporter_class = NULL;
885
886         zipimport_mod = py_import_by_name("zipimport");
887         if (zipimport_mod == NULL)
888                 goto err_out;
889
890         zipimporter_class = PyObject_GetAttrString(zipimport_mod, "zipimporter");
891         if (zipimporter_class == NULL)
892                 goto err_out;
893
894         zipimporter = PyObject_CallFunction(zipimporter_class, "s", path);
895         if (zipimporter == NULL)
896                 goto err_out;
897
898         prefix_obj = PyObject_GetAttrString(zipimporter, "prefix");
899         if (prefix_obj == NULL)
900                 goto err_out;
901
902         files = PyObject_GetAttrString(zipimporter, "_files");
903         if (files == NULL || !PyDict_Check(files))
904                 goto err_out;
905
906         set = PySet_New(NULL);
907         if (set == NULL)
908                 goto err_out;
909
910         if (py_str_as_str(prefix_obj, &prefix) != SRD_OK)
911                 goto err_out;
912
913         prefix_len = strlen(prefix);
914
915         while (PyDict_Next(files, &pos, &key, &value)) {
916                 char *path, *slash;
917                 if (py_str_as_str(key, &path) == SRD_OK) {
918                         if (strlen(path) > prefix_len
919                                         && memcmp(path, prefix, prefix_len) == 0
920                                         && (slash = strchr(path + prefix_len, '/'))) {
921
922                                 modname = PyUnicode_FromStringAndSize(path + prefix_len,
923                                                         slash - (path + prefix_len));
924                                 if (modname == NULL) {
925                                         PyErr_Clear();
926                                 } else {
927                                         PySet_Add(set, modname);
928                                         Py_DECREF(modname);
929                                 }
930                         }
931                         g_free(path);
932                 }
933         }
934         g_free(prefix);
935
936         while ((modname = PySet_Pop(set))) {
937                 char *modname_str;
938                 if (py_str_as_str(modname, &modname_str) == SRD_OK) {
939                         /* The directory name is the module name (e.g. "i2c"). */
940                         srd_decoder_load(modname_str);
941                         g_free(modname_str);
942                 }
943                 Py_DECREF(modname);
944         }
945
946 err_out:
947         Py_XDECREF(set);
948         Py_XDECREF(files);
949         Py_XDECREF(prefix_obj);
950         Py_XDECREF(zipimporter);
951         Py_XDECREF(zipimporter_class);
952         Py_XDECREF(zipimport_mod);
953         PyErr_Clear();
954 }
955
956 static void srd_decoder_load_all_path(char *path)
957 {
958         GDir *dir;
959         const gchar *direntry;
960
961         if (!(dir = g_dir_open(path, 0, NULL))) {
962                 /* Not really fatal */
963                 /* Try zipimport method too */
964                 srd_decoder_load_all_zip_path(path);
965                 return;
966         }
967
968         /* This ignores errors returned by srd_decoder_load(). That
969          * function will have logged the cause, but in any case we
970          * want to continue anyway. */
971         while ((direntry = g_dir_read_name(dir)) != NULL) {
972                 /* The directory name is the module name (e.g. "i2c"). */
973                 srd_decoder_load(direntry);
974         }
975         g_dir_close(dir);
976
977 }
978
979 /**
980  * Load all installed protocol decoders.
981  *
982  * @return SRD_OK upon success, a (negative) error code otherwise.
983  *
984  * @since 0.1.0
985  */
986 SRD_API int srd_decoder_load_all(void)
987 {
988         GSList *l;
989
990         if (!srd_check_init())
991                 return SRD_ERR;
992
993         for (l = searchpaths; l; l = l->next)
994                 srd_decoder_load_all_path(l->data);
995
996         return SRD_OK;
997 }
998
999 /**
1000  * Unload all loaded protocol decoders.
1001  *
1002  * @return SRD_OK upon success, a (negative) error code otherwise.
1003  *
1004  * @since 0.1.0
1005  */
1006 SRD_API int srd_decoder_unload_all(void)
1007 {
1008         g_slist_foreach(pd_list, (GFunc)srd_decoder_unload, NULL);
1009         g_slist_free(pd_list);
1010         pd_list = NULL;
1011
1012         return SRD_OK;
1013 }
1014
1015 /** @} */