]> sigrok.org Git - libsigrokdecode.git/blob - decoder.c
21e24c471d6178610dacd5bdc3885d17221a9e99
[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.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include "libsigrokdecode-internal.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 protocol decoders. */
43 SRD_PRIV GSList *pd_list = NULL;
44
45 /* module_sigrokdecode.c */
46 extern SRD_PRIV PyObject *mod_sigrokdecode;
47
48 /** @endcond */
49
50 /**
51  * Returns the list of supported/loaded protocol decoders.
52  *
53  * This is a GSList containing the names of the decoders as strings.
54  *
55  * @return List of decoders, NULL if none are supported or loaded.
56  *
57  * @since 0.1.0 (but the API changed in 0.2.0)
58  */
59 SRD_API const GSList *srd_decoder_list(void)
60 {
61         return pd_list;
62 }
63
64 /**
65  * Get the decoder with the specified ID.
66  *
67  * @param id The ID string of the decoder to return.
68  *
69  * @return The decoder with the specified ID, or NULL if not found.
70  *
71  * @since 0.1.0
72  */
73 SRD_API struct srd_decoder *srd_decoder_get_by_id(const char *id)
74 {
75         GSList *l;
76         struct srd_decoder *dec;
77
78         for (l = pd_list; l; l = l->next) {
79                 dec = l->data;
80                 if (!strcmp(dec->id, id))
81                         return dec;
82         }
83
84         return NULL;
85 }
86
87 static int get_probes(const struct srd_decoder *d, const char *attr,
88                       GSList **pl)
89 {
90         PyObject *py_probelist, *py_entry;
91         struct srd_probe *p;
92         int ret, num_probes, i;
93
94         if (!PyObject_HasAttrString(d->py_dec, attr))
95                 /* No probes of this type specified. */
96                 return SRD_OK;
97
98         ret = SRD_ERR_PYTHON;
99         py_probelist = py_entry = NULL;
100
101         py_probelist = PyObject_GetAttrString(d->py_dec, attr);
102         if (!PyList_Check(py_probelist)) {
103                 srd_err("Protocol decoder %s %s attribute is not "
104                         "a list.", d->name, attr);
105                 goto err_out;
106         }
107
108         num_probes = PyList_Size(py_probelist);
109         if (num_probes == 0)
110                 /* Empty probelist. */
111                 return SRD_OK;
112
113         for (i = 0; i < num_probes; i++) {
114                 py_entry = PyList_GetItem(py_probelist, i);
115                 if (!PyDict_Check(py_entry)) {
116                         srd_err("Protocol decoder %s %s attribute is not "
117                                 "a list with dict elements.", d->name, attr);
118                         goto err_out;
119                 }
120
121                 if (!(p = g_try_malloc(sizeof(struct srd_probe)))) {
122                         srd_err("Failed to g_malloc() struct srd_probe.");
123                         ret = SRD_ERR_MALLOC;
124                         goto err_out;
125                 }
126
127                 if ((py_dictitem_as_str(py_entry, "id", &p->id)) != SRD_OK)
128                         goto err_out;
129                 if ((py_dictitem_as_str(py_entry, "name", &p->name)) != SRD_OK)
130                         goto err_out;
131                 if ((py_dictitem_as_str(py_entry, "desc", &p->desc)) != SRD_OK)
132                         goto err_out;
133                 p->order = i;
134
135                 *pl = g_slist_append(*pl, p);
136         }
137         ret = SRD_OK;
138
139 err_out:
140         Py_DecRef(py_entry);
141         Py_DecRef(py_probelist);
142
143         return ret;
144 }
145
146 static int get_options(struct srd_decoder *d)
147 {
148         PyObject *py_opts, *py_keys, *py_values, *py_val, *py_desc, *py_default;
149         Py_ssize_t i;
150         struct srd_decoder_option *o;
151         gint64 def_long;
152         int num_keys, overflow, ret;
153         char *key, *def_str;
154
155         ret = SRD_ERR_PYTHON;
156         key = NULL;
157
158         if (!PyObject_HasAttrString(d->py_dec, "options"))
159                 /* That's fine. */
160                 return SRD_OK;
161
162         /* If present, options must be a dictionary. */
163         py_opts = PyObject_GetAttrString(d->py_dec, "options");
164         if (!PyDict_Check(py_opts)) {
165                 srd_err("Protocol decoder %s options attribute is not "
166                         "a dictionary.", d->name);
167                 goto err_out;
168         }
169
170         py_keys = PyDict_Keys(py_opts);
171         py_values = PyDict_Values(py_opts);
172         num_keys = PyList_Size(py_keys);
173         for (i = 0; i < num_keys; i++) {
174                 py_str_as_str(PyList_GetItem(py_keys, i), &key);
175                 srd_dbg("option '%s'", key);
176                 py_val = PyList_GetItem(py_values, i);
177                 if (!PyList_Check(py_val) || PyList_Size(py_val) != 2) {
178                         srd_err("Protocol decoder %s option '%s' value must be "
179                                         "a list with two elements.", d->name, key);
180                         goto err_out;
181                 }
182                 py_desc = PyList_GetItem(py_val, 0);
183                 if (!PyUnicode_Check(py_desc)) {
184                         srd_err("Protocol decoder %s option '%s' has no "
185                                         "description.", d->name, key);
186                         goto err_out;
187                 }
188                 py_default = PyList_GetItem(py_val, 1);
189                 if (!PyUnicode_Check(py_default) && !PyLong_Check(py_default)) {
190                         srd_err("Protocol decoder %s option '%s' has default "
191                                         "of unsupported type '%s'.", d->name, key,
192                                         Py_TYPE(py_default)->tp_name);
193                         goto err_out;
194                 }
195                 if (!(o = g_try_malloc(sizeof(struct srd_decoder_option)))) {
196                         srd_err("option malloc failed");
197                         goto err_out;
198                 }
199                 o->id = g_strdup(key);
200                 py_str_as_str(py_desc, &o->desc);
201                 if (PyUnicode_Check(py_default)) {
202                         /* UTF-8 string */
203                         py_str_as_str(py_default, &def_str);
204                         o->def = g_variant_new_string(def_str);
205                         g_free(def_str);
206                 } else {
207                         /* Long */
208                         def_long = PyLong_AsLongAndOverflow(py_default, &overflow);
209                         if (overflow) {
210                                 /* Value is < LONG_MIN or > LONG_MAX */
211                                 PyErr_Clear();
212                                 srd_err("Protocol decoder %s option '%s' has "
213                                                 "invalid default value.", d->name, key);
214                                 goto err_out;
215                         }
216                         o->def = g_variant_new_int64(def_long);
217                 }
218                 g_variant_ref_sink(o->def);
219                 d->options = g_slist_append(d->options, o);
220         }
221         Py_DecRef(py_keys);
222         Py_DecRef(py_values);
223
224         ret = SRD_OK;
225
226 err_out:
227         Py_XDECREF(py_opts);
228         g_free(key);
229
230         return ret;
231 }
232
233 /**
234  * Load a protocol decoder module into the embedded Python interpreter.
235  *
236  * @param module_name The module name to be loaded.
237  *
238  * @return SRD_OK upon success, a (negative) error code otherwise.
239  *
240  * @since 0.1.0
241  */
242 SRD_API int srd_decoder_load(const char *module_name)
243 {
244         PyObject *py_basedec, *py_method, *py_attr, *py_annlist, *py_ann;
245         struct srd_decoder *d;
246         int alen, ret, i;
247         char **ann;
248         struct srd_probe *p;
249         GSList *l;
250
251         srd_dbg("Loading protocol decoder '%s'.", module_name);
252
253         py_basedec = py_method = py_attr = NULL;
254
255         if (!(d = g_try_malloc0(sizeof(struct srd_decoder)))) {
256                 srd_dbg("Failed to g_malloc() struct srd_decoder.");
257                 ret = SRD_ERR_MALLOC;
258                 goto err_out;
259         }
260
261         ret = SRD_ERR_PYTHON;
262
263         /* Import the Python module. */
264         if (!(d->py_mod = PyImport_ImportModule(module_name))) {
265                 srd_exception_catch("Import of '%s' failed.", module_name);
266                 goto err_out;
267         }
268
269         /* Get the 'Decoder' class as Python object. */
270         if (!(d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder"))) {
271                 /* This generated an AttributeError exception. */
272                 PyErr_Clear();
273                 srd_err("Decoder class not found in protocol decoder %s.",
274                         module_name);
275                 goto err_out;
276         }
277
278         if (!(py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder"))) {
279                 srd_dbg("sigrokdecode module not loaded.");
280                 goto err_out;
281         }
282
283         if (!PyObject_IsSubclass(d->py_dec, py_basedec)) {
284                 srd_err("Decoder class in protocol decoder module %s is not "
285                         "a subclass of sigrokdecode.Decoder.", module_name);
286                 goto err_out;
287         }
288         Py_CLEAR(py_basedec);
289
290         /* Check for a proper start() method. */
291         if (!PyObject_HasAttrString(d->py_dec, "start")) {
292                 srd_err("Protocol decoder %s has no start() method Decoder "
293                         "class.", module_name);
294                 goto err_out;
295         }
296         py_method = PyObject_GetAttrString(d->py_dec, "start");
297         if (!PyFunction_Check(py_method)) {
298                 srd_err("Protocol decoder %s Decoder class attribute 'start' "
299                         "is not a method.", module_name);
300                 goto err_out;
301         }
302         Py_CLEAR(py_method);
303
304         /* Check for a proper decode() method. */
305         if (!PyObject_HasAttrString(d->py_dec, "decode")) {
306                 srd_err("Protocol decoder %s has no decode() method Decoder "
307                         "class.", module_name);
308                 goto err_out;
309         }
310         py_method = PyObject_GetAttrString(d->py_dec, "decode");
311         if (!PyFunction_Check(py_method)) {
312                 srd_err("Protocol decoder %s Decoder class attribute 'decode' "
313                         "is not a method.", module_name);
314                 goto err_out;
315         }
316         Py_CLEAR(py_method);
317
318         if (get_options(d) != SRD_OK)
319                 goto err_out;
320
321         /* Check and import required probes. */
322         if (get_probes(d, "probes", &d->probes) != SRD_OK)
323                 goto err_out;
324
325         /* Check and import optional probes. */
326         if (get_probes(d, "optional_probes", &d->opt_probes) != SRD_OK)
327                 goto err_out;
328
329         /*
330          * Fix order numbers for the optional probes.
331          *
332          * Example:
333          * Required probes: r1, r2, r3. Optional: o1, o2, o3, o4.
334          * 'order' fields in the d->probes list = 0, 1, 2.
335          * 'order' fields in the d->opt_probes list = 3, 4, 5, 6.
336          */
337         for (l = d->opt_probes; l; l = l->next) {
338                 p = l->data;
339                 p->order += g_slist_length(d->probes);
340         }
341
342         /* Store required fields in newly allocated strings. */
343         if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK)
344                 goto err_out;
345
346         if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK)
347                 goto err_out;
348
349         if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK)
350                 goto err_out;
351
352         if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK)
353                 goto err_out;
354
355         if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK)
356                 goto err_out;
357
358         /* Convert class annotation attribute to GSList of **char. */
359         d->annotations = NULL;
360         if (PyObject_HasAttrString(d->py_dec, "annotations")) {
361                 py_annlist = PyObject_GetAttrString(d->py_dec, "annotations");
362                 if (!PyList_Check(py_annlist)) {
363                         srd_err("Protocol decoder module %s annotations "
364                                 "should be a list.", module_name);
365                         goto err_out;
366                 }
367                 alen = PyList_Size(py_annlist);
368                 for (i = 0; i < alen; i++) {
369                         py_ann = PyList_GetItem(py_annlist, i);
370                         if (!PyList_Check(py_ann) || PyList_Size(py_ann) != 2) {
371                                 srd_err("Protocol decoder module %s "
372                                         "annotation %d should be a list with "
373                                         "two elements.", module_name, i + 1);
374                                 goto err_out;
375                         }
376
377                         if (py_strlist_to_char(py_ann, &ann) != SRD_OK) {
378                                 goto err_out;
379                         }
380                         d->annotations = g_slist_append(d->annotations, ann);
381                 }
382         }
383
384         /* Append it to the list of supported/loaded decoders. */
385         pd_list = g_slist_append(pd_list, d);
386
387         ret = SRD_OK;
388
389 err_out:
390         if (ret != SRD_OK) {
391                 Py_XDECREF(py_method);
392                 Py_XDECREF(py_basedec);
393                 Py_XDECREF(d->py_dec);
394                 Py_XDECREF(d->py_mod);
395                 g_free(d);
396         }
397
398         return ret;
399 }
400
401 /**
402  * Return a protocol decoder's docstring.
403  *
404  * @param dec The loaded protocol decoder.
405  *
406  * @return A newly allocated buffer containing the protocol decoder's
407  *         documentation. The caller is responsible for free'ing the buffer.
408  *
409  * @since 0.1.0
410  */
411 SRD_API char *srd_decoder_doc_get(const struct srd_decoder *dec)
412 {
413         PyObject *py_str;
414         char *doc;
415
416         if (!PyObject_HasAttrString(dec->py_mod, "__doc__"))
417                 return NULL;
418
419         if (!(py_str = PyObject_GetAttrString(dec->py_mod, "__doc__"))) {
420                 srd_exception_catch("");
421                 return NULL;
422         }
423
424         doc = NULL;
425         if (py_str != Py_None)
426                 py_str_as_str(py_str, &doc);
427         Py_DecRef(py_str);
428
429         return doc;
430 }
431
432 static void free_probes(GSList *probelist)
433 {
434         GSList *l;
435         struct srd_probe *p;
436
437         if (probelist == NULL)
438                 return;
439
440         for (l = probelist; l; l = l->next) {
441                 p = l->data;
442                 g_free(p->id);
443                 g_free(p->name);
444                 g_free(p->desc);
445                 g_free(p);
446         }
447         g_slist_free(probelist);
448 }
449
450 /**
451  * Unload decoder module.
452  *
453  * @param dec The struct srd_decoder to be unloaded.
454  *
455  * @return SRD_OK upon success, a (negative) error code otherwise.
456  *
457  * @since 0.1.0
458  */
459 SRD_API int srd_decoder_unload(struct srd_decoder *dec)
460 {
461         struct srd_decoder_option *o;
462         GSList *l;
463
464         srd_dbg("Unloading protocol decoder '%s'.", dec->name);
465
466         /*
467          * Since any instances of this decoder need to be released as well,
468          * but they could be anywhere in the stack, just free the entire
469          * stack. A frontend reloading a decoder thus has to restart all
470          * instances, and rebuild the stack.
471          */
472         srd_inst_free_all(NULL);
473
474         for (l = dec->options; l; l = l->next) {
475                 o = l->data;
476                 g_free(o->id);
477                 g_free(o->desc);
478                 g_variant_unref(o->def);
479                 g_free(o);
480         }
481         g_slist_free(dec->options);
482
483         free_probes(dec->probes);
484         free_probes(dec->opt_probes);
485         g_free(dec->id);
486         g_free(dec->name);
487         g_free(dec->longname);
488         g_free(dec->desc);
489         g_free(dec->license);
490
491         /* The module's Decoder class. */
492         Py_XDECREF(dec->py_dec);
493         /* The module itself. */
494         Py_XDECREF(dec->py_mod);
495
496         /* TODO: (g_)free dec itself? */
497
498         return SRD_OK;
499 }
500
501 /**
502  * Load all installed protocol decoders.
503  *
504  * @return SRD_OK upon success, a (negative) error code otherwise.
505  *
506  * @since 0.1.0
507  */
508 SRD_API int srd_decoder_load_all(void)
509 {
510         GDir *dir;
511         GError *error;
512         const gchar *direntry;
513
514         if (!(dir = g_dir_open(DECODERS_DIR, 0, &error))) {
515                 srd_err("Unable to open %s for reading.", DECODERS_DIR);
516                 return SRD_ERR_DECODERS_DIR;
517         }
518
519         while ((direntry = g_dir_read_name(dir)) != NULL) {
520                 /* The directory name is the module name (e.g. "i2c"). */
521                 srd_decoder_load(direntry);
522         }
523         g_dir_close(dir);
524
525         return SRD_OK;
526 }
527
528 /**
529  * Unload all loaded protocol decoders.
530  *
531  * @return SRD_OK upon success, a (negative) error code otherwise.
532  *
533  * @since 0.1.0
534  */
535 SRD_API int srd_decoder_unload_all(void)
536 {
537         GSList *l;
538         struct srd_decoder *dec;
539
540         for (l = pd_list; l; l = l->next) {
541                 dec = l->data;
542                 srd_decoder_unload(dec);
543         }
544
545         return SRD_OK;
546 }
547
548 /** @} */