]> sigrok.org Git - libsigrokdecode.git/blob - instance.c
Turn off excessive logging
[libsigrokdecode.git] / instance.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 "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "libsigrokdecode-internal.h"
23 #include "config.h"
24 #include <glib.h>
25 #include <inttypes.h>
26 #include <stdlib.h>
27 #include <stdint.h>
28
29 /** @cond PRIVATE */
30
31 extern GSList *sessions;
32
33 /* type_logic.c */
34 extern SRD_PRIV PyTypeObject srd_logic_type;
35
36 /** @endcond */
37
38 /**
39  * @file
40  *
41  * Decoder instance handling.
42  */
43
44 /**
45  * @defgroup grp_instances Decoder instances
46  *
47  * Decoder instance handling.
48  *
49  * @{
50  */
51
52 /**
53  * Set one or more options in a decoder instance.
54  *
55  * Handled options are removed from the hash.
56  *
57  * @param di Decoder instance.
58  * @param options A GHashTable of options to set.
59  *
60  * @return SRD_OK upon success, a (negative) error code otherwise.
61  *
62  * @since 0.1.0
63  */
64 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
65                 GHashTable *options)
66 {
67         PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
68         PyObject *py_optlist, *py_classval;
69         Py_UNICODE *py_ustr;
70         GVariant *value;
71         unsigned long long int val_ull;
72         gint64 val_int;
73         int num_optkeys, ret, size, i;
74         const char *val_str;
75         char *dbg, *key;
76
77         if (!di) {
78                 srd_err("Invalid decoder instance.");
79                 return SRD_ERR_ARG;
80         }
81
82         if (!options) {
83                 srd_err("Invalid options GHashTable.");
84                 return SRD_ERR_ARG;
85         }
86
87         if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
88                 /* Decoder has no options. */
89                 if (g_hash_table_size(options) == 0) {
90                         /* No options provided. */
91                         return SRD_OK;
92                 } else {
93                         srd_err("Protocol decoder has no options.");
94                         return SRD_ERR_ARG;
95                 }
96                 return SRD_OK;
97         }
98
99         ret = SRD_ERR_PYTHON;
100         key = NULL;
101         py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
102         py_optlist = py_classval = NULL;
103         py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");
104
105         /* All of these are synthesized objects, so they're good. */
106         py_dec_optkeys = PyDict_Keys(py_dec_options);
107         num_optkeys = PyList_Size(py_dec_optkeys);
108
109         /*
110          * The 'options' dictionary is a class variable, but we need to
111          * change it. Changing it directly will affect the entire class,
112          * so we need to create a new object for it, and populate that
113          * instead.
114          */
115         if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
116                 goto err_out;
117         Py_DECREF(py_di_options);
118         py_di_options = PyDict_New();
119         PyObject_SetAttrString(di->py_inst, "options", py_di_options);
120         for (i = 0; i < num_optkeys; i++) {
121                 /* Get the default class value for this option. */
122                 py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
123                 if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
124                         goto err_out;
125                 if (!(py_classval = PyList_GetItem(py_optlist, 1)))
126                         goto err_out;
127                 if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) {
128                         srd_err("Options of type %s are not yet supported.",
129                                 Py_TYPE(py_classval)->tp_name);
130                         goto err_out;
131                 }
132
133                 if ((value = g_hash_table_lookup(options, key))) {
134                         dbg = g_variant_print(value, TRUE);
135                         srd_dbg("got option '%s' = %s", key, dbg);
136                         g_free(dbg);
137                         /* An override for this option was provided. */
138                         if (PyUnicode_Check(py_classval)) {
139                                 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
140                                         srd_err("Option '%s' requires a string value.", key);
141                                         goto err_out;
142                                 }
143                                 val_str = g_variant_get_string(value, NULL);
144                                 if (!(py_optval = PyUnicode_FromString(val_str))) {
145                                         /* Some UTF-8 encoding error. */
146                                         PyErr_Clear();
147                                         srd_err("Option '%s' requires a UTF-8 string value.", key);
148                                         goto err_out;
149                                 }
150                         } else if (PyLong_Check(py_classval)) {
151                                 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
152                                         srd_err("Option '%s' requires an integer value.", key);
153                                         goto err_out;
154                                 }
155                                 val_int = g_variant_get_int64(value);
156                                 if (!(py_optval = PyLong_FromLong(val_int))) {
157                                         /* ValueError Exception */
158                                         PyErr_Clear();
159                                         srd_err("Option '%s' has invalid integer value.", key);
160                                         goto err_out;
161                                 }
162                         }
163                         g_hash_table_remove(options, key);
164                 } else {
165                         /* Use the class default for this option. */
166                         if (PyUnicode_Check(py_classval)) {
167                                 /* Make a brand new copy of the string. */
168                                 py_ustr = PyUnicode_AS_UNICODE(py_classval);
169                                 size = PyUnicode_GET_SIZE(py_classval);
170                                 py_optval = PyUnicode_FromUnicode(py_ustr, size);
171                         } else if (PyLong_Check(py_classval)) {
172                                 /* Make a brand new copy of the integer. */
173                                 val_ull = PyLong_AsUnsignedLongLong(py_classval);
174                                 if (val_ull == (unsigned long long)-1) {
175                                         /* OverFlowError exception */
176                                         PyErr_Clear();
177                                         srd_err("Invalid integer value for %s: "
178                                                 "expected integer.", key);
179                                         goto err_out;
180                                 }
181                                 if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
182                                         goto err_out;
183                         }
184                 }
185
186                 /*
187                  * If we got here, py_optval holds a known good new reference
188                  * to the instance option to set.
189                  */
190                 if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
191                         goto err_out;
192                 g_free(key);
193                 key = NULL;
194         }
195
196         ret = SRD_OK;
197
198 err_out:
199         Py_XDECREF(py_di_options);
200         Py_XDECREF(py_dec_optkeys);
201         Py_XDECREF(py_dec_options);
202         g_free(key);
203         if (PyErr_Occurred()) {
204                 srd_exception_catch("Stray exception in srd_inst_option_set().");
205                 ret = SRD_ERR_PYTHON;
206         }
207
208         return ret;
209 }
210
211 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_probe_set_all() */
212 static gint compare_probe_id(const struct srd_probe *a, const char *probe_id)
213 {
214         return strcmp(a->id, probe_id);
215 }
216
217 /**
218  * Set all probes in a decoder instance.
219  *
220  * This function sets _all_ probes for the specified decoder instance, i.e.,
221  * it overwrites any probes that were already defined (if any).
222  *
223  * @param di Decoder instance.
224  * @param new_probes A GHashTable of probes to set. Key is probe name, value is
225  *                   the probe number. Samples passed to this instance will be
226  *                   arranged in this order.
227  *
228  * @return SRD_OK upon success, a (negative) error code otherwise.
229  *
230  * @since 0.1.0
231  */
232 SRD_API int srd_inst_probe_set_all(struct srd_decoder_inst *di,
233                 GHashTable *new_probes)
234 {
235         GVariant *probe_val;
236         GList *l;
237         GSList *sl;
238         struct srd_probe *p;
239         int *new_probemap, new_probenum, num_required_probes, num_probes, i;
240         char *probe_id;
241
242         srd_dbg("set probes called for instance %s with list of %d probes",
243                 di->inst_id, g_hash_table_size(new_probes));
244
245         if (g_hash_table_size(new_probes) == 0)
246                 /* No probes provided. */
247                 return SRD_OK;
248
249         if (di->dec_num_probes == 0) {
250                 /* Decoder has no probes. */
251                 srd_err("Protocol decoder %s has no probes to define.",
252                         di->decoder->name);
253                 return SRD_ERR_ARG;
254         }
255
256         new_probemap = NULL;
257
258         if (!(new_probemap = g_try_malloc(sizeof(int) * di->dec_num_probes))) {
259                 srd_err("Failed to g_malloc() new probe map.");
260                 return SRD_ERR_MALLOC;
261         }
262
263         /*
264          * For now, map all indexes to probe -1 (can be overridden later).
265          * This -1 is interpreted as an unspecified probe later.
266          */
267         for (i = 0; i < di->dec_num_probes; i++)
268                 new_probemap[i] = -1;
269
270         num_probes = 0;
271         for (l = g_hash_table_get_keys(new_probes); l; l = l->next) {
272                 probe_id = l->data;
273                 probe_val = g_hash_table_lookup(new_probes, probe_id);
274                 if (!g_variant_is_of_type(probe_val, G_VARIANT_TYPE_INT32)) {
275                         /* Probe name was specified without a value. */
276                         srd_err("No probe number was specified for %s.",
277                                         probe_id);
278                         g_free(new_probemap);
279                         return SRD_ERR_ARG;
280                 }
281                 new_probenum = g_variant_get_int32(probe_val);
282                 if (!(sl = g_slist_find_custom(di->decoder->probes, probe_id,
283                                 (GCompareFunc)compare_probe_id))) {
284                         /* Fall back on optional probes. */
285                         if (!(sl = g_slist_find_custom(di->decoder->opt_probes,
286                              probe_id, (GCompareFunc) compare_probe_id))) {
287                                 srd_err("Protocol decoder %s has no probe "
288                                                 "'%s'.", di->decoder->name, probe_id);
289                                 g_free(new_probemap);
290                                 return SRD_ERR_ARG;
291                         }
292                 }
293                 p = sl->data;
294                 new_probemap[p->order] = new_probenum;
295                 srd_dbg("Setting probe mapping: %s (index %d) = probe %d.",
296                         p->id, p->order, new_probenum);
297                 num_probes++;
298         }
299         di->data_unitsize = (num_probes + 7) / 8;
300
301         srd_dbg("Final probe map:");
302         num_required_probes = g_slist_length(di->decoder->probes);
303         for (i = 0; i < di->dec_num_probes; i++) {
304                 srd_dbg(" - index %d = probe %d (%s)", i, new_probemap[i],
305                         (i < num_required_probes) ? "required" : "optional");
306         }
307
308         g_free(di->dec_probemap);
309         di->dec_probemap = new_probemap;
310
311         return SRD_OK;
312 }
313
314 /**
315  * Create a new protocol decoder instance.
316  *
317  * @param sess The session holding the protocol decoder instance.
318  * @param decoder_id Decoder 'id' field.
319  * @param options GHashtable of options which override the defaults set in
320  *                the decoder class. May be NULL.
321  *
322  * @return Pointer to a newly allocated struct srd_decoder_inst, or
323  *         NULL in case of failure.
324  *
325  * @since 0.3.0
326  */
327 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
328                 const char *decoder_id, GHashTable *options)
329 {
330         int i;
331         struct srd_decoder *dec;
332         struct srd_decoder_inst *di;
333         char *inst_id;
334
335         srd_dbg("Creating new %s instance.", decoder_id);
336
337         if (session_is_valid(sess) != SRD_OK) {
338                 srd_err("Invalid session.");
339                 return NULL;
340         }
341
342         if (!(dec = srd_decoder_get_by_id(decoder_id))) {
343                 srd_err("Protocol decoder %s not found.", decoder_id);
344                 return NULL;
345         }
346
347         if (!(di = g_try_malloc0(sizeof(struct srd_decoder_inst)))) {
348                 srd_err("Failed to g_malloc() instance.");
349                 return NULL;
350         }
351
352         di->decoder = dec;
353         di->sess = sess;
354         if (options) {
355                 inst_id = g_hash_table_lookup(options, "id");
356                 di->inst_id = g_strdup(inst_id ? inst_id : decoder_id);
357                 g_hash_table_remove(options, "id");
358         } else
359                 di->inst_id = g_strdup(decoder_id);
360
361         /*
362          * Prepare a default probe map, where samples come in the
363          * order in which the decoder class defined them.
364          */
365         di->dec_num_probes = g_slist_length(di->decoder->probes) +
366                         g_slist_length(di->decoder->opt_probes);
367         if (di->dec_num_probes) {
368                 if (!(di->dec_probemap =
369                                 g_try_malloc(sizeof(int) * di->dec_num_probes))) {
370                         srd_err("Failed to g_malloc() probe map.");
371                         g_free(di);
372                         return NULL;
373                 }
374                 for (i = 0; i < di->dec_num_probes; i++)
375                         di->dec_probemap[i] = i;
376         }
377         di->data_unitsize = (di->dec_num_probes + 7) / 8;
378
379         /* Create a new instance of this decoder class. */
380         if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
381                 if (PyErr_Occurred())
382                         srd_exception_catch("failed to create %s instance: ",
383                                         decoder_id);
384                 g_free(di->dec_probemap);
385                 g_free(di);
386                 return NULL;
387         }
388
389         if (options && srd_inst_option_set(di, options) != SRD_OK) {
390                 g_free(di->dec_probemap);
391                 g_free(di);
392                 return NULL;
393         }
394
395         /* Instance takes input from a frontend by default. */
396         sess->di_list = g_slist_append(sess->di_list, di);
397
398         return di;
399 }
400
401 /**
402  * Stack a decoder instance on top of another.
403  *
404  * @param sess The session holding the protocol decoder instances.
405  * @param di_from The instance to move.
406  * @param di_to The instance on top of which di_from will be stacked.
407  *
408  * @return SRD_OK upon success, a (negative) error code otherwise.
409  *
410  * @since 0.3.0
411  */
412 SRD_API int srd_inst_stack(struct srd_session *sess,
413                 struct srd_decoder_inst *di_from, struct srd_decoder_inst *di_to)
414 {
415
416         if (session_is_valid(sess) != SRD_OK) {
417                 srd_err("Invalid session.");
418                 return SRD_ERR_ARG;
419         }
420
421         if (!di_from || !di_to) {
422                 srd_err("Invalid from/to instance pair.");
423                 return SRD_ERR_ARG;
424         }
425
426         if (g_slist_find(sess->di_list, di_to)) {
427                 /* Remove from the unstacked list. */
428                 sess->di_list = g_slist_remove(sess->di_list, di_to);
429         }
430
431         /* Stack on top of source di. */
432         di_from->next_di = g_slist_append(di_from->next_di, di_to);
433
434         return SRD_OK;
435 }
436
437 /**
438  * Find a decoder instance by its instance ID.
439  *
440  * Only the bottom level of instances are searched -- instances already stacked
441  * on top of another one will not be found.
442  *
443  * @param sess The session holding the protocol decoder instance.
444  * @param inst_id The instance ID to be found.
445  *
446  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
447  *
448  * @since 0.3.0
449  */
450 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
451                 const char *inst_id)
452 {
453         GSList *l;
454         struct srd_decoder_inst *tmp, *di;
455
456         if (session_is_valid(sess) != SRD_OK) {
457                 srd_err("Invalid session.");
458                 return NULL;
459         }
460
461         di = NULL;
462         for (l = sess->di_list; l; l = l->next) {
463                 tmp = l->data;
464                 if (!strcmp(tmp->inst_id, inst_id)) {
465                         di = tmp;
466                         break;
467                 }
468         }
469
470         return di;
471 }
472
473 static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
474                 struct srd_session *sess, const GSList *stack,
475                 const PyObject *obj)
476 {
477         const GSList *l;
478         struct srd_decoder_inst *tmp, *di;
479
480         if (session_is_valid(sess) != SRD_OK) {
481                 srd_err("Invalid session.");
482                 return NULL;
483         }
484
485         di = NULL;
486         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
487                 tmp = l->data;
488                 if (tmp->py_inst == obj)
489                         di = tmp;
490                 else if (tmp->next_di)
491                         di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
492         }
493
494         return di;
495 }
496
497 /**
498  * Find a decoder instance by its Python object.
499  *
500  * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
501  * This will recurse to find the instance anywhere in the stack tree of all
502  * sessions.
503  *
504  * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
505  *              stack to search. To start searching at the bottom level of
506  *              decoder instances, pass NULL.
507  * @param obj The Python class instantiation.
508  *
509  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
510  *
511  * @private
512  *
513  * @since 0.1.0
514  */
515 SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
516                 const PyObject *obj)
517 {
518         struct srd_decoder_inst *di;
519         struct srd_session *sess;
520         GSList *l;
521
522         di = NULL;
523         for (l = sessions; di == NULL && l != NULL; l = l->next) {
524                 sess = l->data;
525                 di = srd_sess_inst_find_by_obj(sess, stack, obj);
526         }
527
528         return di;
529 }
530
531 /** @private */
532 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
533 {
534         PyObject *py_res;
535         GSList *l;
536         struct srd_decoder_inst *next_di;
537         int ret;
538
539         srd_dbg("Calling start() method on protocol decoder instance %s.",
540                         di->inst_id);
541
542         if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
543                 srd_exception_catch("Protocol decoder instance %s: ",
544                                 di->inst_id);
545                 return SRD_ERR_PYTHON;
546         }
547         Py_DecRef(py_res);
548
549         /* Start all the PDs stacked on top of this one. */
550         for (l = di->next_di; l; l = l->next) {
551                 next_di = l->data;
552                 if ((ret = srd_inst_start(next_di)) != SRD_OK)
553                         return ret;
554         }
555
556         return SRD_OK;
557 }
558
559 /**
560  * Run the specified decoder function.
561  *
562  * @param di The decoder instance to call. Must not be NULL.
563  * @param start_samplenum The starting sample number for the buffer's sample
564  *                        set, relative to the start of capture.
565  * @param end_samplenum The ending sample number for the buffer's sample
566  *                        set, relative to the start of capture.
567  * @param inbuf The buffer to decode. Must not be NULL.
568  * @param inbuflen Length of the buffer. Must be > 0.
569  *
570  * @return SRD_OK upon success, a (negative) error code otherwise.
571  *
572  * @private
573  *
574  * @since 0.1.0
575  */
576 SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
577                 uint64_t start_samplenum, uint64_t end_samplenum,
578                 const uint8_t *inbuf, uint64_t inbuflen)
579 {
580         PyObject *py_res;
581         srd_logic *logic;
582
583         srd_dbg("Calling decode() on instance %s with %" PRIu64 " bytes "
584                 "starting at sample %" PRIu64 ".", di->inst_id, inbuflen,
585                 start_samplenum);
586
587         /* Return an error upon unusable input. */
588         if (!di) {
589                 srd_dbg("empty decoder instance");
590                 return SRD_ERR_ARG;
591         }
592         if (!inbuf) {
593                 srd_dbg("NULL buffer pointer");
594                 return SRD_ERR_ARG;
595         }
596         if (inbuflen == 0) {
597                 srd_dbg("empty buffer");
598                 return SRD_ERR_ARG;
599         }
600
601         /*
602          * Create new srd_logic object. Each iteration around the PD's loop
603          * will fill one sample into this object.
604          */
605         logic = PyObject_New(srd_logic, &srd_logic_type);
606         Py_INCREF(logic);
607         logic->di = (struct srd_decoder_inst *)di;
608         logic->start_samplenum = start_samplenum;
609         logic->itercnt = 0;
610         logic->inbuf = (uint8_t *)inbuf;
611         logic->inbuflen = inbuflen;
612         logic->sample = PyList_New(2);
613         Py_INCREF(logic->sample);
614
615         Py_IncRef(di->py_inst);
616         if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
617                         "KKO", start_samplenum, end_samplenum, logic))) {
618                 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
619                 return SRD_ERR_PYTHON;
620         }
621         Py_DecRef(py_res);
622
623         return SRD_OK;
624 }
625
626 /** @private */
627 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
628 {
629         GSList *l;
630         struct srd_pd_output *pdo;
631
632         srd_dbg("Freeing instance %s", di->inst_id);
633
634         Py_DecRef(di->py_inst);
635         g_free(di->inst_id);
636         g_free(di->dec_probemap);
637         g_slist_free(di->next_di);
638         for (l = di->pd_output; l; l = l->next) {
639                 pdo = l->data;
640                 g_free(pdo->proto_id);
641                 g_free(pdo);
642         }
643         g_slist_free(di->pd_output);
644         g_free(di);
645 }
646
647 /** @private */
648 SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack)
649 {
650         GSList *l;
651         struct srd_decoder_inst *di;
652
653         if (session_is_valid(sess) != SRD_OK) {
654                 srd_err("Invalid session.");
655                 return;
656         }
657
658         di = NULL;
659         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
660                 di = l->data;
661                 if (di->next_di)
662                         srd_inst_free_all(sess, di->next_di);
663                 srd_inst_free(di);
664         }
665         if (!stack) {
666                 g_slist_free(sess->di_list);
667                 sess->di_list = NULL;
668         }
669 }
670
671 /** @} */
672