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