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