]> sigrok.org Git - libsigrokdecode.git/blob - decoder.c
Use uint8_t instead of unsigned char for raw byte data
[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 logic_output_channel_free(void *data)
140 {
141         struct srd_decoder_logic_output_channel *logic_out_ch = data;
142
143         if (!logic_out_ch)
144                 return;
145
146         g_free(logic_out_ch->desc);
147         g_free(logic_out_ch->id);
148         g_free(logic_out_ch);
149 }
150
151 static void decoder_option_free(void *data)
152 {
153         struct srd_decoder_option *opt = data;
154
155         if (!opt)
156                 return;
157
158         g_slist_free_full(opt->values, &variant_free);
159         variant_free(opt->def);
160         g_free(opt->desc);
161         g_free(opt->id);
162         g_free(opt);
163 }
164
165 static void decoder_free(struct srd_decoder *dec)
166 {
167         PyGILState_STATE gstate;
168
169         if (!dec)
170                 return;
171
172         gstate = PyGILState_Ensure();
173         Py_XDECREF(dec->py_dec);
174         Py_XDECREF(dec->py_mod);
175         PyGILState_Release(gstate);
176
177         g_slist_free_full(dec->options, &decoder_option_free);
178         g_slist_free_full(dec->binary, (GDestroyNotify)&g_strfreev);
179         g_slist_free_full(dec->annotation_rows, &annotation_row_free);
180         g_slist_free_full(dec->annotations, (GDestroyNotify)&g_strfreev);
181         g_slist_free_full(dec->opt_channels, &channel_free);
182         g_slist_free_full(dec->channels, &channel_free);
183
184         g_slist_free_full(dec->outputs, g_free);
185         g_slist_free_full(dec->inputs, g_free);
186         g_slist_free_full(dec->tags, g_free);
187         g_free(dec->license);
188         g_free(dec->desc);
189         g_free(dec->longname);
190         g_free(dec->name);
191         g_free(dec->id);
192
193         g_free(dec);
194 }
195
196 static int get_channels(const struct srd_decoder *d, const char *attr,
197                 GSList **out_pdchl, int offset)
198 {
199         PyObject *py_channellist, *py_entry;
200         struct srd_channel *pdch;
201         GSList *pdchl;
202         ssize_t i;
203         PyGILState_STATE gstate;
204
205         gstate = PyGILState_Ensure();
206
207         if (!PyObject_HasAttrString(d->py_dec, attr)) {
208                 /* No channels of this type specified. */
209                 PyGILState_Release(gstate);
210                 return SRD_OK;
211         }
212
213         pdchl = NULL;
214
215         py_channellist = PyObject_GetAttrString(d->py_dec, attr);
216         if (!py_channellist)
217                 goto except_out;
218
219         if (!PyTuple_Check(py_channellist)) {
220                 srd_err("Protocol decoder %s %s attribute is not a tuple.",
221                         d->name, attr);
222                 goto err_out;
223         }
224
225         for (i = PyTuple_Size(py_channellist) - 1; i >= 0; i--) {
226                 py_entry = PyTuple_GetItem(py_channellist, i);
227                 if (!py_entry)
228                         goto except_out;
229
230                 if (!PyDict_Check(py_entry)) {
231                         srd_err("Protocol decoder %s %s attribute is not "
232                                 "a list of dict elements.", d->name, attr);
233                         goto err_out;
234                 }
235                 pdch = g_malloc(sizeof(struct srd_channel));
236                 /* Add to list right away so it doesn't get lost. */
237                 pdchl = g_slist_prepend(pdchl, pdch);
238
239                 if (py_dictitem_as_str(py_entry, "id", &pdch->id) != SRD_OK)
240                         goto err_out;
241                 if (py_dictitem_as_str(py_entry, "name", &pdch->name) != SRD_OK)
242                         goto err_out;
243                 if (py_dictitem_as_str(py_entry, "desc", &pdch->desc) != SRD_OK)
244                         goto err_out;
245
246                 pdch->order = offset + i;
247         }
248
249         Py_DECREF(py_channellist);
250         *out_pdchl = pdchl;
251
252         PyGILState_Release(gstate);
253
254         return SRD_OK;
255
256 except_out:
257         srd_exception_catch("Failed to get %s list of %s decoder",
258                         attr, d->name);
259
260 err_out:
261         g_slist_free_full(pdchl, &channel_free);
262         Py_XDECREF(py_channellist);
263         PyGILState_Release(gstate);
264
265         return SRD_ERR_PYTHON;
266 }
267
268 static int get_options(struct srd_decoder *d)
269 {
270         PyObject *py_opts, *py_opt, *py_str, *py_values, *py_default, *py_item;
271         GSList *options;
272         struct srd_decoder_option *o;
273         GVariant *gvar;
274         ssize_t opt, i;
275         PyGILState_STATE gstate;
276
277         gstate = PyGILState_Ensure();
278
279         if (!PyObject_HasAttrString(d->py_dec, "options")) {
280                 /* No options, that's fine. */
281                 PyGILState_Release(gstate);
282                 return SRD_OK;
283         }
284
285         options = NULL;
286
287         /* If present, options must be a tuple. */
288         py_opts = PyObject_GetAttrString(d->py_dec, "options");
289         if (!py_opts)
290                 goto except_out;
291
292         if (!PyTuple_Check(py_opts)) {
293                 srd_err("Protocol decoder %s: options attribute is not "
294                                 "a tuple.", d->id);
295                 goto err_out;
296         }
297
298         for (opt = PyTuple_Size(py_opts) - 1; opt >= 0; opt--) {
299                 py_opt = PyTuple_GetItem(py_opts, opt);
300                 if (!py_opt)
301                         goto except_out;
302
303                 if (!PyDict_Check(py_opt)) {
304                         srd_err("Protocol decoder %s options: each option "
305                                         "must consist of a dictionary.", d->name);
306                         goto err_out;
307                 }
308
309                 o = g_malloc0(sizeof(struct srd_decoder_option));
310                 /* Add to list right away so it doesn't get lost. */
311                 options = g_slist_prepend(options, o);
312
313                 py_str = PyDict_GetItemString(py_opt, "id");
314                 if (!py_str) {
315                         srd_err("Protocol decoder %s option %zd has no ID.",
316                                 d->name, opt);
317                         goto err_out;
318                 }
319                 if (py_str_as_str(py_str, &o->id) != SRD_OK)
320                         goto err_out;
321
322                 py_str = PyDict_GetItemString(py_opt, "desc");
323                 if (py_str) {
324                         if (py_str_as_str(py_str, &o->desc) != SRD_OK)
325                                 goto err_out;
326                 }
327
328                 py_default = PyDict_GetItemString(py_opt, "default");
329                 if (py_default) {
330                         gvar = py_obj_to_variant(py_default);
331                         if (!gvar) {
332                                 srd_err("Protocol decoder %s option 'default' has "
333                                         "invalid default value.", d->name);
334                                 goto err_out;
335                         }
336                         o->def = g_variant_ref_sink(gvar);
337                 }
338
339                 py_values = PyDict_GetItemString(py_opt, "values");
340                 if (py_values) {
341                         /*
342                          * A default is required if a list of values is
343                          * given, since it's used to verify their type.
344                          */
345                         if (!o->def) {
346                                 srd_err("No default for option '%s'.", o->id);
347                                 goto err_out;
348                         }
349                         if (!PyTuple_Check(py_values)) {
350                                 srd_err("Option '%s' values should be a tuple.", o->id);
351                                 goto err_out;
352                         }
353
354                         for (i = PyTuple_Size(py_values) - 1; i >= 0; i--) {
355                                 py_item = PyTuple_GetItem(py_values, i);
356                                 if (!py_item)
357                                         goto except_out;
358
359                                 if (py_default && (Py_TYPE(py_default) != Py_TYPE(py_item))) {
360                                         srd_err("All values for option '%s' must be "
361                                                 "of the same type as the default.",
362                                                 o->id);
363                                         goto err_out;
364                                 }
365                                 gvar = py_obj_to_variant(py_item);
366                                 if (!gvar) {
367                                         srd_err("Protocol decoder %s option 'values' "
368                                                 "contains invalid value.", d->name);
369                                         goto err_out;
370                                 }
371                                 o->values = g_slist_prepend(o->values,
372                                                 g_variant_ref_sink(gvar));
373                         }
374                 }
375         }
376         d->options = options;
377         Py_DECREF(py_opts);
378         PyGILState_Release(gstate);
379
380         return SRD_OK;
381
382 except_out:
383         srd_exception_catch("Failed to get %s decoder options", d->name);
384
385 err_out:
386         g_slist_free_full(options, &decoder_option_free);
387         Py_XDECREF(py_opts);
388         PyGILState_Release(gstate);
389
390         return SRD_ERR_PYTHON;
391 }
392
393 /* Convert annotation class attribute to GSList of char **. */
394 static int get_annotations(struct srd_decoder *dec)
395 {
396         PyObject *py_annlist, *py_ann;
397         GSList *annotations;
398         char **annpair;
399         ssize_t i;
400         PyGILState_STATE gstate;
401
402         gstate = PyGILState_Ensure();
403
404         if (!PyObject_HasAttrString(dec->py_dec, "annotations")) {
405                 PyGILState_Release(gstate);
406                 return SRD_OK;
407         }
408
409         annotations = NULL;
410
411         py_annlist = PyObject_GetAttrString(dec->py_dec, "annotations");
412         if (!py_annlist)
413                 goto except_out;
414
415         if (!PyTuple_Check(py_annlist)) {
416                 srd_err("Protocol decoder %s annotations should "
417                         "be a tuple.", dec->name);
418                 goto err_out;
419         }
420
421         for (i = PyTuple_Size(py_annlist) - 1; i >= 0; i--) {
422                 py_ann = PyTuple_GetItem(py_annlist, i);
423                 if (!py_ann)
424                         goto except_out;
425
426                 if (!PyTuple_Check(py_ann) || PyTuple_Size(py_ann) != 2) {
427                         srd_err("Protocol decoder %s annotation %zd should "
428                                 "be a tuple with two elements.",
429                                 dec->name, i + 1);
430                         goto err_out;
431                 }
432                 if (py_strseq_to_char(py_ann, &annpair) != SRD_OK)
433                         goto err_out;
434
435                 annotations = g_slist_prepend(annotations, annpair);
436         }
437         dec->annotations = annotations;
438         Py_DECREF(py_annlist);
439         PyGILState_Release(gstate);
440
441         return SRD_OK;
442
443 except_out:
444         srd_exception_catch("Failed to get %s decoder annotations", dec->name);
445
446 err_out:
447         g_slist_free_full(annotations, (GDestroyNotify)&g_strfreev);
448         Py_XDECREF(py_annlist);
449         PyGILState_Release(gstate);
450
451         return SRD_ERR_PYTHON;
452 }
453
454 /* Convert annotation_rows to GSList of 'struct srd_decoder_annotation_row'. */
455 static int get_annotation_rows(struct srd_decoder *dec)
456 {
457         PyObject *py_ann_rows, *py_ann_row, *py_ann_classes, *py_item;
458         GSList *annotation_rows;
459         struct srd_decoder_annotation_row *ann_row;
460         ssize_t i, k;
461         size_t class_idx;
462         PyGILState_STATE gstate;
463
464         gstate = PyGILState_Ensure();
465
466         if (!PyObject_HasAttrString(dec->py_dec, "annotation_rows")) {
467                 PyGILState_Release(gstate);
468                 return SRD_OK;
469         }
470
471         annotation_rows = NULL;
472
473         py_ann_rows = PyObject_GetAttrString(dec->py_dec, "annotation_rows");
474         if (!py_ann_rows)
475                 goto except_out;
476
477         if (!PyTuple_Check(py_ann_rows)) {
478                 srd_err("Protocol decoder %s annotation_rows "
479                         "must be a tuple.", dec->name);
480                 goto err_out;
481         }
482
483         for (i = PyTuple_Size(py_ann_rows) - 1; i >= 0; i--) {
484                 py_ann_row = PyTuple_GetItem(py_ann_rows, i);
485                 if (!py_ann_row)
486                         goto except_out;
487
488                 if (!PyTuple_Check(py_ann_row) || PyTuple_Size(py_ann_row) != 3) {
489                         srd_err("Protocol decoder %s annotation_rows "
490                                 "must contain only tuples of 3 elements.",
491                                 dec->name);
492                         goto err_out;
493                 }
494                 ann_row = g_malloc0(sizeof(struct srd_decoder_annotation_row));
495                 /* Add to list right away so it doesn't get lost. */
496                 annotation_rows = g_slist_prepend(annotation_rows, ann_row);
497
498                 py_item = PyTuple_GetItem(py_ann_row, 0);
499                 if (!py_item)
500                         goto except_out;
501                 if (py_str_as_str(py_item, &ann_row->id) != SRD_OK)
502                         goto err_out;
503
504                 py_item = PyTuple_GetItem(py_ann_row, 1);
505                 if (!py_item)
506                         goto except_out;
507                 if (py_str_as_str(py_item, &ann_row->desc) != SRD_OK)
508                         goto err_out;
509
510                 py_ann_classes = PyTuple_GetItem(py_ann_row, 2);
511                 if (!py_ann_classes)
512                         goto except_out;
513
514                 if (!PyTuple_Check(py_ann_classes)) {
515                         srd_err("Protocol decoder %s annotation_rows tuples "
516                                 "must have a tuple of numbers as 3rd element.",
517                                 dec->name);
518                         goto err_out;
519                 }
520
521                 for (k = PyTuple_Size(py_ann_classes) - 1; k >= 0; k--) {
522                         py_item = PyTuple_GetItem(py_ann_classes, k);
523                         if (!py_item)
524                                 goto except_out;
525
526                         if (!PyLong_Check(py_item)) {
527                                 srd_err("Protocol decoder %s annotation row "
528                                         "class tuple must only contain numbers.",
529                                         dec->name);
530                                 goto err_out;
531                         }
532                         class_idx = PyLong_AsSize_t(py_item);
533                         if (PyErr_Occurred())
534                                 goto except_out;
535
536                         ann_row->ann_classes = g_slist_prepend(ann_row->ann_classes,
537                                         GSIZE_TO_POINTER(class_idx));
538                 }
539         }
540         dec->annotation_rows = annotation_rows;
541         Py_DECREF(py_ann_rows);
542         PyGILState_Release(gstate);
543
544         return SRD_OK;
545
546 except_out:
547         srd_exception_catch("Failed to get %s decoder annotation rows",
548                         dec->name);
549
550 err_out:
551         g_slist_free_full(annotation_rows, &annotation_row_free);
552         Py_XDECREF(py_ann_rows);
553         PyGILState_Release(gstate);
554
555         return SRD_ERR_PYTHON;
556 }
557
558 /* Convert binary classes to GSList of char **. */
559 static int get_binary_classes(struct srd_decoder *dec)
560 {
561         PyObject *py_bin_classes, *py_bin_class;
562         GSList *bin_classes;
563         char **bin;
564         ssize_t i;
565         PyGILState_STATE gstate;
566
567         gstate = PyGILState_Ensure();
568
569         if (!PyObject_HasAttrString(dec->py_dec, "binary")) {
570                 PyGILState_Release(gstate);
571                 return SRD_OK;
572         }
573
574         bin_classes = NULL;
575
576         py_bin_classes = PyObject_GetAttrString(dec->py_dec, "binary");
577         if (!py_bin_classes)
578                 goto except_out;
579
580         if (!PyTuple_Check(py_bin_classes)) {
581                 srd_err("Protocol decoder %s binary classes should "
582                         "be a tuple.", dec->name);
583                 goto err_out;
584         }
585
586         for (i = PyTuple_Size(py_bin_classes) - 1; i >= 0; i--) {
587                 py_bin_class = PyTuple_GetItem(py_bin_classes, i);
588                 if (!py_bin_class)
589                         goto except_out;
590
591                 if (!PyTuple_Check(py_bin_class)
592                                 || PyTuple_Size(py_bin_class) != 2) {
593                         srd_err("Protocol decoder %s binary classes should "
594                                 "consist only of tuples of 2 elements.",
595                                 dec->name);
596                         goto err_out;
597                 }
598                 if (py_strseq_to_char(py_bin_class, &bin) != SRD_OK)
599                         goto err_out;
600
601                 bin_classes = g_slist_prepend(bin_classes, bin);
602         }
603         dec->binary = bin_classes;
604         Py_DECREF(py_bin_classes);
605         PyGILState_Release(gstate);
606
607         return SRD_OK;
608
609 except_out:
610         srd_exception_catch("Failed to get %s decoder binary classes",
611                         dec->name);
612
613 err_out:
614         g_slist_free_full(bin_classes, (GDestroyNotify)&g_strfreev);
615         Py_XDECREF(py_bin_classes);
616         PyGILState_Release(gstate);
617
618         return SRD_ERR_PYTHON;
619 }
620
621 /* Convert logic_output_channels to GSList of 'struct srd_decoder_logic_output_channel'. */
622 static int get_logic_output_channels(struct srd_decoder *dec)
623 {
624         PyObject *py_logic_out_chs, *py_logic_out_ch, *py_item;
625         GSList *logic_out_chs;
626         struct srd_decoder_logic_output_channel *logic_out_ch;
627         ssize_t i;
628         PyGILState_STATE gstate;
629
630         gstate = PyGILState_Ensure();
631
632         if (!PyObject_HasAttrString(dec->py_dec, "logic_output_channels")) {
633                 PyGILState_Release(gstate);
634                 return SRD_OK;
635         }
636
637         logic_out_chs = NULL;
638
639         py_logic_out_chs = PyObject_GetAttrString(dec->py_dec, "logic_output_channels");
640         if (!py_logic_out_chs)
641                 goto except_out;
642
643         if (!PyTuple_Check(py_logic_out_chs)) {
644                 srd_err("Protocol decoder %s logic_output_channels "
645                         "must be a tuple.", dec->name);
646                 goto err_out;
647         }
648
649         for (i = PyTuple_Size(py_logic_out_chs) - 1; i >= 0; i--) {
650                 py_logic_out_ch = PyTuple_GetItem(py_logic_out_chs, i);
651                 if (!py_logic_out_ch)
652                         goto except_out;
653
654                 if (!PyTuple_Check(py_logic_out_ch) || PyTuple_Size(py_logic_out_ch) != 2) {
655                         srd_err("Protocol decoder %s logic_output_channels "
656                                 "must contain only tuples of 2 elements.",
657                                 dec->name);
658                         goto err_out;
659                 }
660                 logic_out_ch = g_malloc0(sizeof(*logic_out_ch));
661                 /* Add to list right away so it doesn't get lost. */
662                 logic_out_chs = g_slist_prepend(logic_out_chs, logic_out_ch);
663
664                 py_item = PyTuple_GetItem(py_logic_out_ch, 0);
665                 if (!py_item)
666                         goto except_out;
667                 if (py_str_as_str(py_item, &logic_out_ch->id) != SRD_OK)
668                         goto err_out;
669
670                 py_item = PyTuple_GetItem(py_logic_out_ch, 1);
671                 if (!py_item)
672                         goto except_out;
673                 if (py_str_as_str(py_item, &logic_out_ch->desc) != SRD_OK)
674                         goto err_out;
675         }
676         dec->logic_output_channels = logic_out_chs;
677         Py_DECREF(py_logic_out_chs);
678         PyGILState_Release(gstate);
679
680         return SRD_OK;
681
682 except_out:
683         srd_exception_catch("Failed to get %s decoder logic output channels",
684                         dec->name);
685
686 err_out:
687         g_slist_free_full(logic_out_chs, &logic_output_channel_free);
688         Py_XDECREF(py_logic_out_chs);
689         PyGILState_Release(gstate);
690
691         return SRD_ERR_PYTHON;
692 }
693
694 /* Check whether the Decoder class defines the named method. */
695 static int check_method(PyObject *py_dec, const char *mod_name,
696                 const char *method_name)
697 {
698         PyObject *py_method;
699         int is_callable;
700         PyGILState_STATE gstate;
701
702         gstate = PyGILState_Ensure();
703
704         py_method = PyObject_GetAttrString(py_dec, method_name);
705         if (!py_method) {
706                 srd_exception_catch("Protocol decoder %s Decoder class "
707                                 "has no %s() method", mod_name, method_name);
708                 PyGILState_Release(gstate);
709                 return SRD_ERR_PYTHON;
710         }
711
712         is_callable = PyCallable_Check(py_method);
713         Py_DECREF(py_method);
714
715         PyGILState_Release(gstate);
716
717         if (!is_callable) {
718                 srd_err("Protocol decoder %s Decoder class attribute '%s' "
719                         "is not a method.", mod_name, method_name);
720                 return SRD_ERR_PYTHON;
721         }
722
723         return SRD_OK;
724 }
725
726 /**
727  * Get the API version of the specified decoder.
728  *
729  * @param d The decoder to use. Must not be NULL.
730  *
731  * @return The API version of the decoder, or 0 upon errors.
732  *
733  * @private
734  */
735 SRD_PRIV long srd_decoder_apiver(const struct srd_decoder *d)
736 {
737         PyObject *py_apiver;
738         long apiver;
739         PyGILState_STATE gstate;
740
741         if (!d)
742                 return 0;
743
744         gstate = PyGILState_Ensure();
745
746         py_apiver = PyObject_GetAttrString(d->py_dec, "api_version");
747         apiver = (py_apiver && PyLong_Check(py_apiver))
748                         ? PyLong_AsLong(py_apiver) : 0;
749         Py_XDECREF(py_apiver);
750
751         PyGILState_Release(gstate);
752
753         return apiver;
754 }
755
756 static gboolean contains_duplicates(GSList *list)
757 {
758         for (GSList *l1 = list; l1; l1 = l1->next) {
759                 for (GSList *l2 = l1->next; l2; l2 = l2->next)
760                         if (!strcmp(l1->data, l2->data))
761                                 return TRUE;
762         }
763
764         return FALSE;
765 }
766
767 static gboolean contains_duplicate_ids(GSList *list1, GSList *list2)
768 {
769         for (GSList *l1 = list1; l1; l1 = l1->next) {
770                 unsigned int cnt = 0;
771                 const char **s1 = l1->data;
772                 for (GSList *l2 = list2; l2; l2 = l2->next) {
773                         const char **s2 = l2->data;
774                         if (!strcmp(s1[0], s2[0]))
775                                 cnt++;
776                         if ((list1 == list2) && cnt > 1)
777                                 return TRUE;
778                         if ((list1 != list2) && cnt > 0)
779                                 return TRUE;
780                 }
781         }
782
783         return FALSE;
784 }
785
786 static gboolean contains_duplicate_row_ids(GSList *list1, GSList *list2)
787 {
788         for (GSList *l1 = list1; l1; l1 = l1->next) {
789                 unsigned int cnt = 0;
790                 const struct srd_decoder_annotation_row *r1 = l1->data;
791                 for (GSList *l2 = list2; l2; l2 = l2->next) {
792                         const struct srd_decoder_annotation_row *r2 = l2->data;
793                         if (!strcmp(r1->id, r2->id))
794                                 cnt++;
795                         if (cnt > 1)
796                                 return TRUE;
797                 }
798         }
799
800         return FALSE;
801 }
802
803 /**
804  * Load a protocol decoder module into the embedded Python interpreter.
805  *
806  * @param module_name The module name to be loaded.
807  *
808  * @return SRD_OK upon success, a (negative) error code otherwise.
809  *
810  * @since 0.1.0
811  */
812 SRD_API int srd_decoder_load(const char *module_name)
813 {
814         PyObject *py_basedec;
815         struct srd_decoder *d;
816         long apiver;
817         int is_subclass;
818         const char *fail_txt;
819         PyGILState_STATE gstate;
820
821         if (!srd_check_init())
822                 return SRD_ERR;
823
824         if (!module_name)
825                 return SRD_ERR_ARG;
826
827         gstate = PyGILState_Ensure();
828
829         if (PyDict_GetItemString(PyImport_GetModuleDict(), module_name)) {
830                 /* Module was already imported. */
831                 PyGILState_Release(gstate);
832                 return SRD_OK;
833         }
834
835         d = g_malloc0(sizeof(struct srd_decoder));
836         fail_txt = NULL;
837
838         d->py_mod = py_import_by_name(module_name);
839         if (!d->py_mod) {
840                 fail_txt = "import by name failed";
841                 goto except_out;
842         }
843
844         if (!mod_sigrokdecode) {
845                 srd_err("sigrokdecode module not loaded.");
846                 fail_txt = "sigrokdecode(3) not loaded";
847                 goto err_out;
848         }
849
850         /* Get the 'Decoder' class as Python object. */
851         d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder");
852         if (!d->py_dec) {
853                 fail_txt = "no 'Decoder' attribute in imported module";
854                 goto except_out;
855         }
856
857         py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder");
858         if (!py_basedec) {
859                 fail_txt = "no 'Decoder' attribute in sigrokdecode(3)";
860                 goto except_out;
861         }
862
863         is_subclass = PyObject_IsSubclass(d->py_dec, py_basedec);
864         Py_DECREF(py_basedec);
865
866         if (!is_subclass) {
867                 srd_err("Decoder class in protocol decoder module %s is not "
868                         "a subclass of sigrokdecode.Decoder.", module_name);
869                 fail_txt = "not a subclass of sigrokdecode.Decoder";
870                 goto err_out;
871         }
872
873         /*
874          * Check that this decoder has the correct PD API version.
875          * PDs of different API versions are incompatible and cannot work.
876          */
877         apiver = srd_decoder_apiver(d);
878         if (apiver != 3) {
879                 srd_exception_catch("Only PD API version 3 is supported, "
880                         "decoder %s has version %ld", module_name, apiver);
881                 fail_txt = "API version mismatch";
882                 goto err_out;
883         }
884
885         /* Check Decoder class for required methods. */
886
887         if (check_method(d->py_dec, module_name, "reset") != SRD_OK) {
888                 fail_txt = "no 'reset()' method";
889                 goto err_out;
890         }
891
892         if (check_method(d->py_dec, module_name, "start") != SRD_OK) {
893                 fail_txt = "no 'start()' method";
894                 goto err_out;
895         }
896
897         if (check_method(d->py_dec, module_name, "decode") != SRD_OK) {
898                 fail_txt = "no 'decode()' method";
899                 goto err_out;
900         }
901
902         /* Store required fields in newly allocated strings. */
903         if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK) {
904                 fail_txt = "no 'id' attribute";
905                 goto err_out;
906         }
907
908         if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK) {
909                 fail_txt = "no 'name' attribute";
910                 goto err_out;
911         }
912
913         if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK) {
914                 fail_txt = "no 'longname' attribute";
915                 goto err_out;
916         }
917
918         if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK) {
919                 fail_txt = "no 'desc' attribute";
920                 goto err_out;
921         }
922
923         if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK) {
924                 fail_txt = "no 'license' attribute";
925                 goto err_out;
926         }
927
928         if (py_attr_as_strlist(d->py_dec, "inputs", &(d->inputs)) != SRD_OK) {
929                 fail_txt = "missing or malformed 'inputs' attribute";
930                 goto err_out;
931         }
932
933         if (py_attr_as_strlist(d->py_dec, "outputs", &(d->outputs)) != SRD_OK) {
934                 fail_txt = "missing or malformed 'outputs' attribute";
935                 goto err_out;
936         }
937
938         if (py_attr_as_strlist(d->py_dec, "tags", &(d->tags)) != SRD_OK) {
939                 fail_txt = "missing or malformed 'tags' attribute";
940                 goto err_out;
941         }
942
943         /* All options and their default values. */
944         if (get_options(d) != SRD_OK) {
945                 fail_txt = "cannot get options";
946                 goto err_out;
947         }
948
949         /* Check and import required channels. */
950         if (get_channels(d, "channels", &d->channels, 0) != SRD_OK) {
951                 fail_txt = "cannot get channels";
952                 goto err_out;
953         }
954
955         /* Check and import optional channels. */
956         if (get_channels(d, "optional_channels", &d->opt_channels,
957                                 g_slist_length(d->channels)) != SRD_OK) {
958                 fail_txt = "cannot get optional channels";
959                 goto err_out;
960         }
961
962         if (get_annotations(d) != SRD_OK) {
963                 fail_txt = "cannot get annotations";
964                 goto err_out;
965         }
966
967         if (get_annotation_rows(d) != SRD_OK) {
968                 fail_txt = "cannot get annotation rows";
969                 goto err_out;
970         }
971
972         if (get_binary_classes(d) != SRD_OK) {
973                 fail_txt = "cannot get binary classes";
974                 goto err_out;
975         }
976
977         if (contains_duplicates(d->inputs)) {
978                 fail_txt = "duplicate input IDs";
979                 goto err_out;
980         }
981
982         if (contains_duplicates(d->outputs)) {
983                 fail_txt = "duplicate output IDs";
984                 goto err_out;
985         }
986
987         if (contains_duplicates(d->tags)) {
988                 fail_txt = "duplicate tags";
989                 goto err_out;
990         }
991
992         if (contains_duplicate_ids(d->channels, d->channels)) {
993                 fail_txt = "duplicate channel IDs";
994                 goto err_out;
995         }
996
997         if (contains_duplicate_ids(d->opt_channels, d->opt_channels)) {
998                 fail_txt = "duplicate optional channel IDs";
999                 goto err_out;
1000         }
1001
1002         if (contains_duplicate_ids(d->channels, d->opt_channels)) {
1003                 fail_txt = "channel and optional channel IDs contain duplicates";
1004                 goto err_out;
1005         }
1006
1007         if (contains_duplicate_ids(d->options, d->options)) {
1008                 fail_txt = "duplicate option IDs";
1009                 goto err_out;
1010         }
1011
1012         if (contains_duplicate_ids(d->annotations, d->annotations)) {
1013                 fail_txt = "duplicate annotation class IDs";
1014                 goto err_out;
1015         }
1016
1017         if (contains_duplicate_row_ids(d->annotation_rows, d->annotation_rows)) {
1018                 fail_txt = "duplicate annotation row IDs";
1019                 goto err_out;
1020         }
1021
1022         if (contains_duplicate_ids(d->annotations, d->annotation_rows)) {
1023                 fail_txt = "annotation class/row IDs contain duplicates";
1024                 goto err_out;
1025         }
1026
1027         if (contains_duplicate_ids(d->binary, d->binary)) {
1028                 fail_txt = "duplicate binary class IDs";
1029                 goto err_out;
1030         }
1031
1032         if (get_logic_output_channels(d) != SRD_OK) {
1033                 fail_txt = "cannot get logic output channels";
1034                 goto err_out;
1035         }
1036
1037         PyGILState_Release(gstate);
1038
1039         /* Append it to the list of loaded decoders. */
1040         pd_list = g_slist_append(pd_list, d);
1041
1042         return SRD_OK;
1043
1044 except_out:
1045         /* Don't show a message for the "common" directory, it's not a PD. */
1046         if (strcmp(module_name, "common")) {
1047                 srd_exception_catch("Failed to load decoder %s: %s",
1048                                     module_name, fail_txt);
1049         }
1050         fail_txt = NULL;
1051
1052 err_out:
1053         if (fail_txt)
1054                 srd_err("Failed to load decoder %s: %s", module_name, fail_txt);
1055         decoder_free(d);
1056         PyGILState_Release(gstate);
1057
1058         return SRD_ERR_PYTHON;
1059 }
1060
1061 /**
1062  * Return a protocol decoder's docstring.
1063  *
1064  * @param dec The loaded protocol decoder. Must not be NULL.
1065  *
1066  * @return A newly allocated buffer containing the protocol decoder's
1067  *         documentation. The caller is responsible for free'ing the buffer.
1068  *
1069  * @since 0.1.0
1070  */
1071 SRD_API char *srd_decoder_doc_get(const struct srd_decoder *dec)
1072 {
1073         PyObject *py_str;
1074         char *doc;
1075         PyGILState_STATE gstate;
1076
1077         if (!srd_check_init())
1078                 return NULL;
1079
1080         if (!dec || !dec->py_mod)
1081                 return NULL;
1082
1083         gstate = PyGILState_Ensure();
1084
1085         if (!PyObject_HasAttrString(dec->py_mod, "__doc__"))
1086                 goto err;
1087
1088         if (!(py_str = PyObject_GetAttrString(dec->py_mod, "__doc__"))) {
1089                 srd_exception_catch("Failed to get docstring");
1090                 goto err;
1091         }
1092
1093         doc = NULL;
1094         if (py_str != Py_None)
1095                 py_str_as_str(py_str, &doc);
1096         Py_DECREF(py_str);
1097
1098         PyGILState_Release(gstate);
1099
1100         return doc;
1101
1102 err:
1103         PyGILState_Release(gstate);
1104
1105         return NULL;
1106 }
1107
1108 /**
1109  * Unload the specified protocol decoder.
1110  *
1111  * @param dec The struct srd_decoder to be unloaded.
1112  *
1113  * @return SRD_OK upon success, a (negative) error code otherwise.
1114  *
1115  * @since 0.1.0
1116  */
1117 SRD_API int srd_decoder_unload(struct srd_decoder *dec)
1118 {
1119         struct srd_session *sess;
1120         GSList *l;
1121
1122         if (!srd_check_init())
1123                 return SRD_ERR;
1124
1125         if (!dec)
1126                 return SRD_ERR_ARG;
1127
1128         /*
1129          * Since any instances of this decoder need to be released as well,
1130          * but they could be anywhere in the stack, just free the entire
1131          * stack. A frontend reloading a decoder thus has to restart all
1132          * instances, and rebuild the stack.
1133          */
1134         for (l = sessions; l; l = l->next) {
1135                 sess = l->data;
1136                 srd_inst_free_all(sess);
1137         }
1138
1139         /* Remove the PD from the list of loaded decoders. */
1140         pd_list = g_slist_remove(pd_list, dec);
1141
1142         decoder_free(dec);
1143
1144         return SRD_OK;
1145 }
1146
1147 static void srd_decoder_load_all_zip_path(char *zip_path)
1148 {
1149         PyObject *zipimport_mod, *zipimporter_class, *zipimporter;
1150         PyObject *prefix_obj, *files, *key, *value, *set, *modname;
1151         Py_ssize_t pos = 0;
1152         char *prefix;
1153         size_t prefix_len;
1154         PyGILState_STATE gstate;
1155
1156         set = files = prefix_obj = zipimporter = zipimporter_class = NULL;
1157
1158         gstate = PyGILState_Ensure();
1159
1160         zipimport_mod = py_import_by_name("zipimport");
1161         if (zipimport_mod == NULL)
1162                 goto err_out;
1163
1164         zipimporter_class = PyObject_GetAttrString(zipimport_mod, "zipimporter");
1165         if (zipimporter_class == NULL)
1166                 goto err_out;
1167
1168         zipimporter = PyObject_CallFunction(zipimporter_class, "s", zip_path);
1169         if (zipimporter == NULL)
1170                 goto err_out;
1171
1172         prefix_obj = PyObject_GetAttrString(zipimporter, "prefix");
1173         if (prefix_obj == NULL)
1174                 goto err_out;
1175
1176         files = PyObject_GetAttrString(zipimporter, "_files");
1177         if (files == NULL || !PyDict_Check(files))
1178                 goto err_out;
1179
1180         set = PySet_New(NULL);
1181         if (set == NULL)
1182                 goto err_out;
1183
1184         if (py_str_as_str(prefix_obj, &prefix) != SRD_OK)
1185                 goto err_out;
1186
1187         prefix_len = strlen(prefix);
1188
1189         while (PyDict_Next(files, &pos, &key, &value)) {
1190                 char *path, *slash;
1191                 if (py_str_as_str(key, &path) == SRD_OK) {
1192                         if (strlen(path) > prefix_len
1193                                         && memcmp(path, prefix, prefix_len) == 0
1194                                         && (slash = strchr(path + prefix_len, '/'))) {
1195
1196                                 modname = PyUnicode_FromStringAndSize(path + prefix_len,
1197                                                         slash - (path + prefix_len));
1198                                 if (modname == NULL) {
1199                                         PyErr_Clear();
1200                                 } else {
1201                                         PySet_Add(set, modname);
1202                                         Py_DECREF(modname);
1203                                 }
1204                         }
1205                         g_free(path);
1206                 }
1207         }
1208         g_free(prefix);
1209
1210         while ((modname = PySet_Pop(set))) {
1211                 char *modname_str;
1212                 if (py_str_as_str(modname, &modname_str) == SRD_OK) {
1213                         /* The directory name is the module name (e.g. "i2c"). */
1214                         srd_decoder_load(modname_str);
1215                         g_free(modname_str);
1216                 }
1217                 Py_DECREF(modname);
1218         }
1219
1220 err_out:
1221         Py_XDECREF(set);
1222         Py_XDECREF(files);
1223         Py_XDECREF(prefix_obj);
1224         Py_XDECREF(zipimporter);
1225         Py_XDECREF(zipimporter_class);
1226         Py_XDECREF(zipimport_mod);
1227         PyErr_Clear();
1228         PyGILState_Release(gstate);
1229 }
1230
1231 static void srd_decoder_load_all_path(char *path)
1232 {
1233         GDir *dir;
1234         const gchar *direntry;
1235
1236         if (!(dir = g_dir_open(path, 0, NULL))) {
1237                 /* Not really fatal. Try zipimport method too. */
1238                 srd_decoder_load_all_zip_path(path);
1239                 return;
1240         }
1241
1242         /*
1243          * This ignores errors returned by srd_decoder_load(). That
1244          * function will have logged the cause, but in any case we
1245          * want to continue anyway.
1246          */
1247         while ((direntry = g_dir_read_name(dir)) != NULL) {
1248                 /* The directory name is the module name (e.g. "i2c"). */
1249                 srd_decoder_load(direntry);
1250         }
1251         g_dir_close(dir);
1252 }
1253
1254 /**
1255  * Load all installed protocol decoders.
1256  *
1257  * @return SRD_OK upon success, a (negative) error code otherwise.
1258  *
1259  * @since 0.1.0
1260  */
1261 SRD_API int srd_decoder_load_all(void)
1262 {
1263         GSList *l;
1264
1265         if (!srd_check_init())
1266                 return SRD_ERR;
1267
1268         for (l = searchpaths; l; l = l->next)
1269                 srd_decoder_load_all_path(l->data);
1270
1271         return SRD_OK;
1272 }
1273
1274 static void srd_decoder_unload_cb(void *arg, void *ignored)
1275 {
1276         (void)ignored;
1277
1278         srd_decoder_unload((struct srd_decoder *)arg);
1279 }
1280
1281 /**
1282  * Unload all loaded protocol decoders.
1283  *
1284  * @return SRD_OK upon success, a (negative) error code otherwise.
1285  *
1286  * @since 0.1.0
1287  */
1288 SRD_API int srd_decoder_unload_all(void)
1289 {
1290         g_slist_foreach(pd_list, srd_decoder_unload_cb, NULL);
1291         g_slist_free(pd_list);
1292         pd_list = NULL;
1293
1294         return SRD_OK;
1295 }
1296
1297 /** @} */