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