]> sigrok.org Git - libsigrokdecode.git/blob - decoder.c
52c913aeea0ad6bec6e9f876c4ee93714a112818
[libsigrokdecode.git] / decoder.c
1 /*
2  * This file is part of the sigrok 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 "sigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include "sigrokdecode-internal.h"
24 #include <glib.h>
25
26 /** @cond PRIVATE */
27
28 /* The list of protocol decoders. */
29 SRD_PRIV GSList *pd_list = NULL;
30
31 /* module_sigrokdecode.c */
32 extern SRD_PRIV PyObject *mod_sigrokdecode;
33
34 /** @endcond */
35
36 /**
37  * Returns the list of supported/loaded protocol decoders.
38  *
39  * This is a GSList containing the names of the decoders as strings.
40  *
41  * @return List of decoders, NULL if none are supported or loaded.
42  */
43 SRD_API const GSList *srd_decoder_list(void)
44 {
45         return pd_list;
46 }
47
48 /**
49  * Get the decoder with the specified ID.
50  *
51  * @param id The ID string of the decoder to return.
52  *
53  * @return The decoder with the specified ID, or NULL if not found.
54  */
55 SRD_API struct srd_decoder *srd_decoder_get_by_id(const char *id)
56 {
57         GSList *l;
58         struct srd_decoder *dec;
59
60         for (l = pd_list; l; l = l->next) {
61                 dec = l->data;
62                 if (!strcmp(dec->id, id))
63                         return dec;
64         }
65
66         return NULL;
67 }
68
69 static int get_probes(const struct srd_decoder *d, const char *attr,
70                       GSList **pl)
71 {
72         PyObject *py_probelist, *py_entry;
73         struct srd_probe *p;
74         int ret, num_probes, i;
75
76         if (!PyObject_HasAttrString(d->py_dec, attr))
77                 /* No probes of this type specified. */
78                 return SRD_OK;
79
80         ret = SRD_ERR_PYTHON;
81         py_probelist = py_entry = NULL;
82
83         py_probelist = PyObject_GetAttrString(d->py_dec, attr);
84         if (!PyList_Check(py_probelist)) {
85                 srd_err("Protocol decoder %s %s attribute is not "
86                         "a list.", d->name, attr);
87                 goto err_out;
88         }
89
90         num_probes = PyList_Size(py_probelist);
91         if (num_probes == 0)
92                 /* Empty probelist. */
93                 return SRD_OK;
94
95         for (i = 0; i < num_probes; i++) {
96                 py_entry = PyList_GetItem(py_probelist, i);
97                 if (!PyDict_Check(py_entry)) {
98                         srd_err("Protocol decoder %s %s attribute is not "
99                                 "a list with dict elements.", d->name, attr);
100                         goto err_out;
101                 }
102
103                 if (!(p = g_try_malloc(sizeof(struct srd_probe)))) {
104                         srd_err("Failed to g_malloc() struct srd_probe.");
105                         ret = SRD_ERR_MALLOC;
106                         goto err_out;
107                 }
108
109                 if ((py_dictitem_as_str(py_entry, "id", &p->id)) != SRD_OK)
110                         goto err_out;
111                 if ((py_dictitem_as_str(py_entry, "name", &p->name)) != SRD_OK)
112                         goto err_out;
113                 if ((py_dictitem_as_str(py_entry, "desc", &p->desc)) != SRD_OK)
114                         goto err_out;
115                 p->order = i;
116
117                 *pl = g_slist_append(*pl, p);
118         }
119         ret = SRD_OK;
120
121 err_out:
122         Py_DecRef(py_entry);
123         Py_DecRef(py_probelist);
124
125         return ret;
126 }
127
128 /**
129  * Load a protocol decoder module into the embedded Python interpreter.
130  *
131  * @param module_name The module name to be loaded.
132  *
133  * @return SRD_OK upon success, a (negative) error code otherwise.
134  */
135 SRD_API int srd_decoder_load(const char *module_name)
136 {
137         PyObject *py_basedec, *py_method, *py_attr, *py_annlist, *py_ann;
138         struct srd_decoder *d;
139         int alen, ret, i;
140         char **ann;
141         struct srd_probe *p;
142         GSList *l;
143
144         srd_dbg("Loading protocol decoder '%s'.", module_name);
145
146         py_basedec = py_method = py_attr = NULL;
147
148         if (!(d = g_try_malloc0(sizeof(struct srd_decoder)))) {
149                 srd_dbg("Failed to g_malloc() struct srd_decoder.");
150                 ret = SRD_ERR_MALLOC;
151                 goto err_out;
152         }
153
154         ret = SRD_ERR_PYTHON;
155
156         /* Import the Python module. */
157         if (!(d->py_mod = PyImport_ImportModule(module_name))) {
158                 srd_exception_catch("Import of '%s' failed.", module_name);
159                 goto err_out;
160         }
161
162         /* Get the 'Decoder' class as Python object. */
163         if (!(d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder"))) {
164                 /* This generated an AttributeError exception. */
165                 PyErr_Clear();
166                 srd_err("Decoder class not found in protocol decoder %s.",
167                         module_name);
168                 goto err_out;
169         }
170
171         if (!(py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder"))) {
172                 srd_dbg("sigrokdecode module not loaded.");
173                 goto err_out;
174         }
175
176         if (!PyObject_IsSubclass(d->py_dec, py_basedec)) {
177                 srd_err("Decoder class in protocol decoder module %s is not "
178                         "a subclass of sigrokdecode.Decoder.", module_name);
179                 goto err_out;
180         }
181         Py_CLEAR(py_basedec);
182
183         /* Check for a proper start() method. */
184         if (!PyObject_HasAttrString(d->py_dec, "start")) {
185                 srd_err("Protocol decoder %s has no start() method Decoder "
186                         "class.", module_name);
187                 goto err_out;
188         }
189         py_method = PyObject_GetAttrString(d->py_dec, "start");
190         if (!PyFunction_Check(py_method)) {
191                 srd_err("Protocol decoder %s Decoder class attribute 'start' "
192                         "is not a method.", module_name);
193                 goto err_out;
194         }
195         Py_CLEAR(py_method);
196
197         /* Check for a proper decode() method. */
198         if (!PyObject_HasAttrString(d->py_dec, "decode")) {
199                 srd_err("Protocol decoder %s has no decode() method Decoder "
200                         "class.", module_name);
201                 goto err_out;
202         }
203         py_method = PyObject_GetAttrString(d->py_dec, "decode");
204         if (!PyFunction_Check(py_method)) {
205                 srd_err("Protocol decoder %s Decoder class attribute 'decode' "
206                         "is not a method.", module_name);
207                 goto err_out;
208         }
209         Py_CLEAR(py_method);
210
211         /* If present, options must be a dictionary. */
212         if (PyObject_HasAttrString(d->py_dec, "options")) {
213                 py_attr = PyObject_GetAttrString(d->py_dec, "options");
214                 if (!PyDict_Check(py_attr)) {
215                         srd_err("Protocol decoder %s options attribute is not "
216                                 "a dictionary.", d->name);
217                         Py_DecRef(py_attr);
218                         goto err_out;
219                 }
220                 Py_DecRef(py_attr);
221         }
222
223         /* Check and import required probes. */
224         if (get_probes(d, "probes", &d->probes) != SRD_OK)
225                 goto err_out;
226
227         /* Check and import optional probes. */
228         if (get_probes(d, "optional_probes", &d->opt_probes) != SRD_OK)
229                 goto err_out;
230
231         /*
232          * Fix order numbers for the optional probes.
233          *
234          * Example:
235          * Required probes: r1, r2, r3. Optional: o1, o2, o3, o4.
236          * 'order' fields in the d->probes list = 0, 1, 2.
237          * 'order' fields in the d->opt_probes list = 3, 4, 5, 6.
238          */
239         for (l = d->opt_probes; l; l = l->next) {
240                 p = l->data;
241                 p->order += g_slist_length(d->probes);
242         }
243
244         /* Store required fields in newly allocated strings. */
245         if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK)
246                 goto err_out;
247
248         if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK)
249                 goto err_out;
250
251         if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK)
252                 goto err_out;
253
254         if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK)
255                 goto err_out;
256
257         if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK)
258                 goto err_out;
259
260         /* Convert class annotation attribute to GSList of **char. */
261         d->annotations = NULL;
262         if (PyObject_HasAttrString(d->py_dec, "annotations")) {
263                 py_annlist = PyObject_GetAttrString(d->py_dec, "annotations");
264                 if (!PyList_Check(py_annlist)) {
265                         srd_err("Protocol decoder module %s annotations "
266                                 "should be a list.", module_name);
267                         goto err_out;
268                 }
269                 alen = PyList_Size(py_annlist);
270                 for (i = 0; i < alen; i++) {
271                         py_ann = PyList_GetItem(py_annlist, i);
272                         if (!PyList_Check(py_ann) || PyList_Size(py_ann) != 2) {
273                                 srd_err("Protocol decoder module %s "
274                                         "annotation %d should be a list with "
275                                         "two elements.", module_name, i + 1);
276                                 goto err_out;
277                         }
278
279                         if (py_strlist_to_char(py_ann, &ann) != SRD_OK) {
280                                 goto err_out;
281                         }
282                         d->annotations = g_slist_append(d->annotations, ann);
283                 }
284         }
285
286         /* Append it to the list of supported/loaded decoders. */
287         pd_list = g_slist_append(pd_list, d);
288
289         ret = SRD_OK;
290
291 err_out:
292         if (ret != SRD_OK) {
293                 Py_XDECREF(py_method);
294                 Py_XDECREF(py_basedec);
295                 Py_XDECREF(d->py_dec);
296                 Py_XDECREF(d->py_mod);
297                 g_free(d);
298         }
299
300         return ret;
301 }
302
303 /**
304  * Return a protocol decoder's docstring.
305  *
306  * @param dec The loaded protocol decoder.
307  *
308  * @return A newly allocated buffer containing the protocol decoder's
309  *         documentation. The caller is responsible for free'ing the buffer.
310  */
311 SRD_API char *srd_decoder_doc_get(const struct srd_decoder *dec)
312 {
313         PyObject *py_str;
314         char *doc;
315
316         if (!PyObject_HasAttrString(dec->py_mod, "__doc__"))
317                 return NULL;
318
319         if (!(py_str = PyObject_GetAttrString(dec->py_mod, "__doc__"))) {
320                 srd_exception_catch("");
321                 return NULL;
322         }
323
324         doc = NULL;
325         if (py_str != Py_None)
326                 py_str_as_str(py_str, &doc);
327         Py_DecRef(py_str);
328
329         return doc;
330 }
331
332 static void free_probes(GSList *probelist)
333 {
334         GSList *l;
335         struct srd_probe *p;
336
337         if (probelist == NULL)
338                 return;
339
340         for (l = probelist; l; l = l->next) {
341                 p = l->data;
342                 g_free(p->id);
343                 g_free(p->name);
344                 g_free(p->desc);
345                 g_free(p);
346         }
347         g_slist_free(probelist);
348 }
349
350 /**
351  * Unload decoder module.
352  *
353  * @param dec The struct srd_decoder to be unloaded.
354  *
355  * @return SRD_OK upon success, a (negative) error code otherwise.
356  */
357 SRD_API int srd_decoder_unload(struct srd_decoder *dec)
358 {
359         srd_dbg("Unloading protocol decoder '%s'.", dec->name);
360
361         /*
362          * Since any instances of this decoder need to be released as well,
363          * but they could be anywhere in the stack, just free the entire
364          * stack. A frontend reloading a decoder thus has to restart all
365          * instances, and rebuild the stack.
366          */
367         srd_inst_free_all(NULL);
368
369         free_probes(dec->probes);
370         free_probes(dec->opt_probes);
371         g_free(dec->id);
372         g_free(dec->name);
373         g_free(dec->longname);
374         g_free(dec->desc);
375         g_free(dec->license);
376
377         /* The module's Decoder class. */
378         Py_XDECREF(dec->py_dec);
379         /* The module itself. */
380         Py_XDECREF(dec->py_mod);
381
382         /* TODO: (g_)free dec itself? */
383
384         return SRD_OK;
385 }
386
387 /**
388  * Load all installed protocol decoders.
389  *
390  * @return SRD_OK upon success, a (negative) error code otherwise.
391  */
392 SRD_API int srd_decoder_load_all(void)
393 {
394         GDir *dir;
395         GError *error;
396         const gchar *direntry;
397
398         if (!(dir = g_dir_open(DECODERS_DIR, 0, &error))) {
399                 srd_err("Unable to open %s for reading.", DECODERS_DIR);
400                 return SRD_ERR_DECODERS_DIR;
401         }
402
403         while ((direntry = g_dir_read_name(dir)) != NULL) {
404                 /* The directory name is the module name (e.g. "i2c"). */
405                 srd_decoder_load(direntry);
406         }
407         g_dir_close(dir);
408
409         return SRD_OK;
410 }
411
412 /**
413  * Unload all loaded protocol decoders.
414  *
415  * @return SRD_OK upon success, a (negative) error code otherwise.
416  */
417 SRD_API int srd_decoder_unload_all(void)
418 {
419         GSList *l;
420         struct srd_decoder *dec;
421
422         for (l = pd_list; l; l = l->next) {
423                 dec = l->data;
424                 srd_decoder_unload(dec);
425         }
426
427         return SRD_OK;
428 }