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