]> sigrok.org Git - libsigrokdecode.git/blob - instance.c
Fix multiple PyObject_SetAttrString() related leaks.
[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 <config.h>
22 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include "libsigrokdecode.h"
24 #include <glib.h>
25 #include <inttypes.h>
26 #include <stdlib.h>
27 #include <stdint.h>
28
29 /** @cond PRIVATE */
30
31 extern SRD_PRIV GSList *sessions;
32
33 /** @endcond */
34
35 /**
36  * @file
37  *
38  * Decoder instance handling.
39  */
40
41 /**
42  * @defgroup grp_instances Decoder instances
43  *
44  * Decoder instance handling.
45  *
46  * @{
47  */
48
49 static void oldpins_array_seed(struct srd_decoder_inst *di)
50 {
51         size_t count;
52         GArray *arr;
53
54         if (!di)
55                 return;
56         if (di->old_pins_array)
57                 return;
58
59         count = di->dec_num_channels;
60         arr = g_array_sized_new(FALSE, TRUE, sizeof(uint8_t), count);
61         g_array_set_size(arr, count);
62         memset(arr->data, SRD_INITIAL_PIN_SAME_AS_SAMPLE0, count);
63         di->old_pins_array = arr;
64 }
65
66 static void oldpins_array_free(struct srd_decoder_inst *di)
67 {
68         if (!di)
69                 return;
70         if (!di->old_pins_array)
71                 return;
72
73         srd_dbg("%s: Releasing initial pin state.", di->inst_id);
74
75         g_array_free(di->old_pins_array, TRUE);
76         di->old_pins_array = NULL;
77 }
78
79 /**
80  * Set one or more options in a decoder instance.
81  *
82  * Handled options are removed from the hash.
83  *
84  * @param di Decoder instance.
85  * @param options A GHashTable of options to set.
86  *
87  * @return SRD_OK upon success, a (negative) error code otherwise.
88  *
89  * @since 0.1.0
90  */
91 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
92                 GHashTable *options)
93 {
94         struct srd_decoder_option *sdo;
95         PyObject *py_di_options, *py_optval;
96         GVariant *value;
97         GSList *l;
98         double val_double;
99         gint64 val_int;
100         int ret;
101         const char *val_str;
102         PyGILState_STATE gstate;
103
104         if (!di) {
105                 srd_err("Invalid decoder instance.");
106                 return SRD_ERR_ARG;
107         }
108
109         if (!options) {
110                 srd_err("Invalid options GHashTable.");
111                 return SRD_ERR_ARG;
112         }
113
114         gstate = PyGILState_Ensure();
115
116         if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
117                 /* Decoder has no options. */
118                 PyGILState_Release(gstate);
119                 if (g_hash_table_size(options) == 0) {
120                         /* No options provided. */
121                         return SRD_OK;
122                 } else {
123                         srd_err("Protocol decoder has no options.");
124                         return SRD_ERR_ARG;
125                 }
126                 return SRD_OK;
127         }
128
129         ret = SRD_ERR_PYTHON;
130         py_optval = NULL;
131
132         /*
133          * The 'options' tuple is a class variable, but we need to
134          * change it. Changing it directly will affect the entire class,
135          * so we need to create a new object for it, and populate that
136          * instead.
137          */
138         if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
139                 goto err_out;
140         Py_DECREF(py_di_options);
141         py_di_options = PyDict_New();
142         PyObject_SetAttrString(di->py_inst, "options", py_di_options);
143         Py_DECREF(py_di_options);
144
145         for (l = di->decoder->options; l; l = l->next) {
146                 sdo = l->data;
147                 if ((value = g_hash_table_lookup(options, sdo->id))) {
148                         /* A value was supplied for this option. */
149                         if (!g_variant_type_equal(g_variant_get_type(value),
150                                   g_variant_get_type(sdo->def))) {
151                                 srd_err("Option '%s' should have the same type "
152                                         "as the default value.", sdo->id);
153                                 goto err_out;
154                         }
155                 } else {
156                         /* Use default for this option. */
157                         value = sdo->def;
158                 }
159                 if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
160                         val_str = g_variant_get_string(value, NULL);
161                         if (!(py_optval = PyUnicode_FromString(val_str))) {
162                                 /* Some UTF-8 encoding error. */
163                                 PyErr_Clear();
164                                 srd_err("Option '%s' requires a UTF-8 string value.", sdo->id);
165                                 goto err_out;
166                         }
167                 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
168                         val_int = g_variant_get_int64(value);
169                         if (!(py_optval = PyLong_FromLong(val_int))) {
170                                 /* ValueError Exception */
171                                 PyErr_Clear();
172                                 srd_err("Option '%s' has invalid integer value.", sdo->id);
173                                 goto err_out;
174                         }
175                 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_DOUBLE)) {
176                         val_double = g_variant_get_double(value);
177                         if (!(py_optval = PyFloat_FromDouble(val_double))) {
178                                 /* ValueError Exception */
179                                 PyErr_Clear();
180                                 srd_err("Option '%s' has invalid float value.",
181                                         sdo->id);
182                                 goto err_out;
183                         }
184                 }
185                 if (PyDict_SetItemString(py_di_options, sdo->id, py_optval) == -1)
186                         goto err_out;
187                 /* Not harmful even if we used the default. */
188                 g_hash_table_remove(options, sdo->id);
189         }
190         if (g_hash_table_size(options) != 0)
191                 srd_warn("Unknown options specified for '%s'", di->inst_id);
192
193         ret = SRD_OK;
194
195 err_out:
196         Py_XDECREF(py_optval);
197         if (PyErr_Occurred()) {
198                 srd_exception_catch("Stray exception in srd_inst_option_set()");
199                 ret = SRD_ERR_PYTHON;
200         }
201         PyGILState_Release(gstate);
202
203         return ret;
204 }
205
206 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_channel_set_all(). */
207 static gint compare_channel_id(const struct srd_channel *pdch,
208                         const char *channel_id)
209 {
210         return strcmp(pdch->id, channel_id);
211 }
212
213 /**
214  * Set all channels in a decoder instance.
215  *
216  * This function sets _all_ channels for the specified decoder instance, i.e.,
217  * it overwrites any channels that were already defined (if any).
218  *
219  * @param di Decoder instance.
220  * @param new_channels A GHashTable of channels to set. Key is channel name,
221  *                     value is the channel number. Samples passed to this
222  *                     instance will be arranged in this order.
223  *
224  * @return SRD_OK upon success, a (negative) error code otherwise.
225  *
226  * @since 0.4.0
227  */
228 SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
229                 GHashTable *new_channels)
230 {
231         GVariant *channel_val;
232         GList *l;
233         GSList *sl;
234         struct srd_channel *pdch;
235         int *new_channelmap, new_channelnum, num_required_channels, i;
236         char *channel_id;
237
238         srd_dbg("Setting channels for instance %s with list of %d channels.",
239                 di->inst_id, g_hash_table_size(new_channels));
240
241         if (g_hash_table_size(new_channels) == 0)
242                 /* No channels provided. */
243                 return SRD_OK;
244
245         if (di->dec_num_channels == 0) {
246                 /* Decoder has no channels. */
247                 srd_err("Protocol decoder %s has no channels to define.",
248                         di->decoder->name);
249                 return SRD_ERR_ARG;
250         }
251
252         new_channelmap = g_malloc0(sizeof(int) * di->dec_num_channels);
253
254         /*
255          * For now, map all indexes to channel -1 (can be overridden later).
256          * This -1 is interpreted as an unspecified channel later.
257          */
258         for (i = 0; i < di->dec_num_channels; i++)
259                 new_channelmap[i] = -1;
260
261         for (l = g_hash_table_get_keys(new_channels); l; l = l->next) {
262                 channel_id = l->data;
263                 channel_val = g_hash_table_lookup(new_channels, channel_id);
264                 if (!g_variant_is_of_type(channel_val, G_VARIANT_TYPE_INT32)) {
265                         /* Channel name was specified without a value. */
266                         srd_err("No channel number was specified for %s.",
267                                         channel_id);
268                         g_free(new_channelmap);
269                         return SRD_ERR_ARG;
270                 }
271                 new_channelnum = g_variant_get_int32(channel_val);
272                 if (!(sl = g_slist_find_custom(di->decoder->channels, channel_id,
273                                 (GCompareFunc)compare_channel_id))) {
274                         /* Fall back on optional channels. */
275                         if (!(sl = g_slist_find_custom(di->decoder->opt_channels,
276                              channel_id, (GCompareFunc)compare_channel_id))) {
277                                 srd_err("Protocol decoder %s has no channel "
278                                         "'%s'.", di->decoder->name, channel_id);
279                                 g_free(new_channelmap);
280                                 return SRD_ERR_ARG;
281                         }
282                 }
283                 pdch = sl->data;
284                 new_channelmap[pdch->order] = new_channelnum;
285                 srd_dbg("Setting channel mapping: %s (PD ch idx %d) = input data ch idx %d.",
286                         pdch->id, pdch->order, new_channelnum);
287         }
288
289         srd_dbg("Final channel map:");
290         num_required_channels = g_slist_length(di->decoder->channels);
291         for (i = 0; i < di->dec_num_channels; i++) {
292                 GSList *ll = g_slist_nth(di->decoder->channels, i);
293                 if (!ll)
294                         ll = g_slist_nth(di->decoder->opt_channels,
295                                 i - num_required_channels);
296                 pdch = ll->data;
297                 srd_dbg(" - PD ch idx %d (%s) = input data ch idx %d (%s)", i,
298                         pdch->id, new_channelmap[i],
299                         (i < num_required_channels) ? "required" : "optional");
300         }
301
302         /* Report an error if not all required channels were specified. */
303         for (i = 0; i < num_required_channels; i++) {
304                 if (new_channelmap[i] != -1)
305                         continue;
306                 pdch = g_slist_nth(di->decoder->channels, i)->data;
307                 srd_err("Required channel '%s' (index %d) was not specified.",
308                         pdch->id, i);
309                 g_free(new_channelmap);
310                 return SRD_ERR;
311         }
312
313         g_free(di->dec_channelmap);
314         di->dec_channelmap = new_channelmap;
315
316         return SRD_OK;
317 }
318
319 /**
320  * Create a new protocol decoder instance.
321  *
322  * @param sess The session holding the protocol decoder instance.
323  *             Must not be NULL.
324  * @param decoder_id Decoder 'id' field.
325  * @param options GHashtable of options which override the defaults set in
326  *                the decoder class. May be NULL.
327  *
328  * @return Pointer to a newly allocated struct srd_decoder_inst, or
329  *         NULL in case of failure.
330  *
331  * @since 0.3.0
332  */
333 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
334                 const char *decoder_id, GHashTable *options)
335 {
336         int i;
337         struct srd_decoder *dec;
338         struct srd_decoder_inst *di;
339         char *inst_id;
340         PyGILState_STATE gstate;
341
342         i = 1;
343
344         if (!sess)
345                 return NULL;
346
347         if (!(dec = srd_decoder_get_by_id(decoder_id))) {
348                 srd_err("Protocol decoder %s not found.", decoder_id);
349                 return NULL;
350         }
351
352         di = g_malloc0(sizeof(struct srd_decoder_inst));
353
354         di->decoder = dec;
355         di->sess = sess;
356
357         if (options) {
358                 inst_id = g_hash_table_lookup(options, "id");
359                 if (inst_id)
360                         di->inst_id = g_strdup(inst_id);
361                 g_hash_table_remove(options, "id");
362         }
363
364         /* Create a unique instance ID (as none was provided). */
365         if (!di->inst_id) {
366                 di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
367                 while (srd_inst_find_by_id(sess, di->inst_id)) {
368                         g_free(di->inst_id);
369                         di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
370                 }
371         }
372
373         /*
374          * Prepare a default channel map, where samples come in the
375          * order in which the decoder class defined them.
376          */
377         di->dec_num_channels = g_slist_length(di->decoder->channels) +
378                         g_slist_length(di->decoder->opt_channels);
379         if (di->dec_num_channels) {
380                 di->dec_channelmap =
381                                 g_malloc(sizeof(int) * di->dec_num_channels);
382                 for (i = 0; i < di->dec_num_channels; i++)
383                         di->dec_channelmap[i] = i;
384                 /*
385                  * Will be used to prepare a sample at every iteration
386                  * of the instance's decode() method.
387                  */
388                 di->channel_samples = g_malloc(di->dec_num_channels);
389         }
390
391         /* Default to the initial pins being the same as in sample 0. */
392         oldpins_array_seed(di);
393
394         gstate = PyGILState_Ensure();
395
396         /* Create a new instance of this decoder class. */
397         if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
398                 if (PyErr_Occurred())
399                         srd_exception_catch("Failed to create %s instance",
400                                         decoder_id);
401                 PyGILState_Release(gstate);
402                 g_free(di->dec_channelmap);
403                 g_free(di);
404                 return NULL;
405         }
406
407         PyGILState_Release(gstate);
408
409         if (options && srd_inst_option_set(di, options) != SRD_OK) {
410                 g_free(di->dec_channelmap);
411                 g_free(di);
412                 return NULL;
413         }
414
415         di->condition_list = NULL;
416         di->match_array = NULL;
417         di->abs_start_samplenum = 0;
418         di->abs_end_samplenum = 0;
419         di->inbuf = NULL;
420         di->inbuflen = 0;
421         di->abs_cur_samplenum = 0;
422         di->thread_handle = NULL;
423         di->got_new_samples = FALSE;
424         di->handled_all_samples = FALSE;
425         di->want_wait_terminate = FALSE;
426         di->decoder_state = SRD_OK;
427
428         /*
429          * Strictly speaking initialization of statically allocated
430          * condition and mutex variables (or variables allocated on the
431          * stack) is not required, but won't harm either. Explicitly
432          * running init() will better match subsequent clear() calls.
433          */
434         g_cond_init(&di->got_new_samples_cond);
435         g_cond_init(&di->handled_all_samples_cond);
436         g_mutex_init(&di->data_mutex);
437
438         /* Instance takes input from a frontend by default. */
439         sess->di_list = g_slist_append(sess->di_list, di);
440         srd_dbg("Creating new %s instance %s.", decoder_id, di->inst_id);
441
442         return di;
443 }
444
445 static void srd_inst_join_decode_thread(struct srd_decoder_inst *di)
446 {
447         if (!di)
448                 return;
449         if (!di->thread_handle)
450                 return;
451
452         srd_dbg("%s: Joining decoder thread.", di->inst_id);
453
454         /*
455          * Terminate potentially running threads which still
456          * execute the decoder instance's decode() method.
457          */
458         srd_dbg("%s: Raising want_term, sending got_new.", di->inst_id);
459         g_mutex_lock(&di->data_mutex);
460         di->want_wait_terminate = TRUE;
461         g_cond_signal(&di->got_new_samples_cond);
462         g_mutex_unlock(&di->data_mutex);
463
464         srd_dbg("%s: Running join().", di->inst_id);
465         (void)g_thread_join(di->thread_handle);
466         srd_dbg("%s: Call to join() done.", di->inst_id);
467         di->thread_handle = NULL;
468
469         /*
470          * Reset condition and mutex variables, such that next
471          * operations on them will find them in a clean state.
472          */
473         g_cond_clear(&di->got_new_samples_cond);
474         g_cond_init(&di->got_new_samples_cond);
475         g_cond_clear(&di->handled_all_samples_cond);
476         g_cond_init(&di->handled_all_samples_cond);
477         g_mutex_clear(&di->data_mutex);
478         g_mutex_init(&di->data_mutex);
479 }
480
481 static void srd_inst_reset_state(struct srd_decoder_inst *di)
482 {
483         if (!di)
484                 return;
485
486         srd_dbg("%s: Resetting decoder state.", di->inst_id);
487
488         /* Reset internal state of the decoder. */
489         condition_list_free(di);
490         match_array_free(di);
491         di->abs_start_samplenum = 0;
492         di->abs_end_samplenum = 0;
493         di->inbuf = NULL;
494         di->inbuflen = 0;
495         di->abs_cur_samplenum = 0;
496         oldpins_array_free(di);
497         di->got_new_samples = FALSE;
498         di->handled_all_samples = FALSE;
499         di->want_wait_terminate = FALSE;
500         di->decoder_state = SRD_OK;
501         /* Conditions and mutex got reset after joining the thread. */
502 }
503
504 /**
505  * Stack a decoder instance on top of another.
506  *
507  * @param sess The session holding the protocol decoder instances.
508  *             Must not be NULL.
509  * @param di_bottom The instance on top of which di_top will be stacked.
510  * @param di_top The instance to go on top.
511  *
512  * @return SRD_OK upon success, a (negative) error code otherwise.
513  *
514  * @since 0.3.0
515  */
516 SRD_API int srd_inst_stack(struct srd_session *sess,
517                 struct srd_decoder_inst *di_bottom,
518                 struct srd_decoder_inst *di_top)
519 {
520         if (!sess)
521                 return SRD_ERR_ARG;
522
523         if (!di_bottom || !di_top) {
524                 srd_err("Invalid from/to instance pair.");
525                 return SRD_ERR_ARG;
526         }
527
528         if (g_slist_find(sess->di_list, di_top)) {
529                 /* Remove from the unstacked list. */
530                 sess->di_list = g_slist_remove(sess->di_list, di_top);
531         }
532
533         /*
534          * Check if there's at least one matching input/output pair
535          * for the stacked PDs. We warn if that's not the case, but it's
536          * not a hard error for the time being.
537          */
538         gboolean at_least_one_match = FALSE;
539         for (GSList *out = di_bottom->decoder->outputs; out; out = out->next) {
540                 const char *o = out->data;
541                 for (GSList *in = di_top->decoder->inputs; in; in = in->next) {
542                         const char *i = in->data;
543                         if (!strcmp(o, i)) {
544                                 at_least_one_match = TRUE;
545                                 break;
546                         }
547                 }
548         }
549
550         if (!at_least_one_match)
551                 srd_warn("No matching in-/output when stacking %s onto %s.",
552                         di_top->inst_id, di_bottom->inst_id);
553
554         /* Stack on top of source di. */
555         di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
556
557         srd_dbg("Stacking %s onto %s.", di_top->inst_id, di_bottom->inst_id);
558
559         return SRD_OK;
560 }
561
562 /**
563  * Search a decoder instance and its stack for instance ID.
564  *
565  * @param[in] inst_id ID to search for.
566  * @param[in] stack A decoder instance, potentially with stacked instances.
567  *
568  * @return The matching instance, or NULL.
569  */
570 static struct srd_decoder_inst *srd_inst_find_by_id_stack(const char *inst_id,
571                 struct srd_decoder_inst *stack)
572 {
573         const GSList *l;
574         struct srd_decoder_inst *tmp, *di;
575
576         if (!strcmp(stack->inst_id, inst_id))
577                 return stack;
578
579         /* Otherwise, look recursively in our stack. */
580         di = NULL;
581         if (stack->next_di) {
582                 for (l = stack->next_di; l; l = l->next) {
583                         tmp = l->data;
584                         if (!strcmp(tmp->inst_id, inst_id)) {
585                                 di = tmp;
586                                 break;
587                         }
588                 }
589         }
590
591         return di;
592 }
593
594 /**
595  * Find a decoder instance by its instance ID.
596  *
597  * This will recurse to find the instance anywhere in the stack tree of the
598  * given session.
599  *
600  * @param sess The session holding the protocol decoder instance.
601  *             Must not be NULL.
602  * @param inst_id The instance ID to be found.
603  *
604  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
605  *
606  * @since 0.3.0
607  */
608 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
609                 const char *inst_id)
610 {
611         GSList *l;
612         struct srd_decoder_inst *tmp, *di;
613
614         if (!sess)
615                 return NULL;
616
617         di = NULL;
618         for (l = sess->di_list; l; l = l->next) {
619                 tmp = l->data;
620                 if ((di = srd_inst_find_by_id_stack(inst_id, tmp)) != NULL)
621                         break;
622         }
623
624         return di;
625 }
626
627 /**
628  * Set the list of initial (assumed) pin values.
629  *
630  * @param di Decoder instance to use. Must not be NULL.
631  * @param initial_pins A GArray of uint8_t values. Must not be NULL.
632  *
633  * @since 0.5.0
634  */
635 SRD_API int srd_inst_initial_pins_set_all(struct srd_decoder_inst *di, GArray *initial_pins)
636 {
637         int i;
638         GString *s;
639
640         if (!di) {
641                 srd_err("Invalid decoder instance.");
642                 return SRD_ERR_ARG;
643         }
644
645         if (!initial_pins)
646                 return SRD_ERR_ARG;
647
648         if (initial_pins->len != (guint)di->dec_num_channels) {
649                 srd_err("Incorrect number of channels (need %d, got %d).",
650                         di->dec_num_channels, initial_pins->len);
651                 return SRD_ERR_ARG;
652         }
653
654         /* Sanity-check initial pin state values. */
655         for (i = 0; i < di->dec_num_channels; i++) {
656                 if (initial_pins->data[i] <= 2)
657                         continue;
658                 srd_err("Invalid initial channel %d pin state: %d.",
659                         i, initial_pins->data[i]);
660                 return SRD_ERR_ARG;
661         }
662
663         s = g_string_sized_new(100);
664         oldpins_array_seed(di);
665         for (i = 0; i < di->dec_num_channels; i++) {
666                 di->old_pins_array->data[i] = initial_pins->data[i];
667                 g_string_append_printf(s, "%d, ", di->old_pins_array->data[i]);
668         }
669         s = g_string_truncate(s, s->len - 2);
670         srd_dbg("Initial pins: %s.", s->str);
671         g_string_free(s, TRUE);
672
673         return SRD_OK;
674 }
675
676 /** @private */
677 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
678 {
679         PyObject *py_res, *py_samplenum;
680         GSList *l;
681         struct srd_decoder_inst *next_di;
682         int ret;
683         PyGILState_STATE gstate;
684
685         srd_dbg("Calling start() of instance %s.", di->inst_id);
686
687         gstate = PyGILState_Ensure();
688
689         /* Run self.start(). */
690         if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
691                 srd_exception_catch("Protocol decoder instance %s",
692                                 di->inst_id);
693                 PyGILState_Release(gstate);
694                 return SRD_ERR_PYTHON;
695         }
696         Py_DecRef(py_res);
697
698         /* Set self.samplenum to 0. */
699         py_samplenum = PyLong_FromLong(0);
700         PyObject_SetAttrString(di->py_inst, "samplenum", py_samplenum);
701         Py_DECREF(py_samplenum);
702
703         /* Set self.matched to None. */
704         PyObject_SetAttrString(di->py_inst, "matched", Py_None);
705
706         PyGILState_Release(gstate);
707
708         /* Start all the PDs stacked on top of this one. */
709         for (l = di->next_di; l; l = l->next) {
710                 next_di = l->data;
711                 if ((ret = srd_inst_start(next_di)) != SRD_OK)
712                         return ret;
713         }
714
715         return SRD_OK;
716 }
717
718 /**
719  * Check whether the specified sample matches the specified term.
720  *
721  * In the case of SRD_TERM_SKIP, this function can modify
722  * term->num_samples_already_skipped.
723  *
724  * @param old_sample The value of the previous sample (0/1).
725  * @param sample The value of the current sample (0/1).
726  * @param term The term that should be checked for a match. Must not be NULL.
727  *
728  * @retval TRUE The current sample matches the specified term.
729  * @retval FALSE The current sample doesn't match the specified term, or an
730  *               invalid term was provided.
731  *
732  * @private
733  */
734 __attribute__((always_inline))
735 static inline gboolean sample_matches(uint8_t old_sample, uint8_t sample, struct srd_term *term)
736 {
737         /* Caller ensures term != NULL. */
738
739         switch (term->type) {
740         case SRD_TERM_HIGH:
741                 if (sample == 1)
742                         return TRUE;
743                 break;
744         case SRD_TERM_LOW:
745                 if (sample == 0)
746                         return TRUE;
747                 break;
748         case SRD_TERM_RISING_EDGE:
749                 if (old_sample == 0 && sample == 1)
750                         return TRUE;
751                 break;
752         case SRD_TERM_FALLING_EDGE:
753                 if (old_sample == 1 && sample == 0)
754                         return TRUE;
755                 break;
756         case SRD_TERM_EITHER_EDGE:
757                 if ((old_sample == 1 && sample == 0) || (old_sample == 0 && sample == 1))
758                         return TRUE;
759                 break;
760         case SRD_TERM_NO_EDGE:
761                 if ((old_sample == 0 && sample == 0) || (old_sample == 1 && sample == 1))
762                         return TRUE;
763                 break;
764         case SRD_TERM_SKIP:
765                 if (term->num_samples_already_skipped == term->num_samples_to_skip)
766                         return TRUE;
767                 term->num_samples_already_skipped++;
768                 break;
769         default:
770                 srd_err("Unknown term type %d.", term->type);
771                 break;
772         }
773
774         return FALSE;
775 }
776
777 /** @private */
778 SRD_PRIV void match_array_free(struct srd_decoder_inst *di)
779 {
780         if (!di || !di->match_array)
781                 return;
782
783         g_array_free(di->match_array, TRUE);
784         di->match_array = NULL;
785 }
786
787 /** @private */
788 SRD_PRIV void condition_list_free(struct srd_decoder_inst *di)
789 {
790         GSList *l, *ll;
791
792         if (!di)
793                 return;
794
795         for (l = di->condition_list; l; l = l->next) {
796                 ll = l->data;
797                 if (ll)
798                         g_slist_free_full(ll, g_free);
799         }
800
801         g_slist_free(di->condition_list);
802         di->condition_list = NULL;
803 }
804
805 static gboolean have_non_null_conds(const struct srd_decoder_inst *di)
806 {
807         GSList *l, *cond;
808
809         if (!di)
810                 return FALSE;
811
812         for (l = di->condition_list; l; l = l->next) {
813                 cond = l->data;
814                 if (cond)
815                         return TRUE;
816         }
817
818         return FALSE;
819 }
820
821 static void update_old_pins_array(struct srd_decoder_inst *di,
822                 const uint8_t *sample_pos)
823 {
824         uint8_t sample;
825         int i, byte_offset, bit_offset;
826
827         if (!di || !di->dec_channelmap || !sample_pos)
828                 return;
829
830         oldpins_array_seed(di);
831         for (i = 0; i < di->dec_num_channels; i++) {
832                 byte_offset = di->dec_channelmap[i] / 8;
833                 bit_offset = di->dec_channelmap[i] % 8;
834                 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
835                 di->old_pins_array->data[i] = sample;
836         }
837 }
838
839 static void update_old_pins_array_initial_pins(struct srd_decoder_inst *di)
840 {
841         uint8_t sample;
842         int i, byte_offset, bit_offset;
843         const uint8_t *sample_pos;
844
845         if (!di || !di->dec_channelmap)
846                 return;
847
848         sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
849
850         oldpins_array_seed(di);
851         for (i = 0; i < di->dec_num_channels; i++) {
852                 if (di->old_pins_array->data[i] != SRD_INITIAL_PIN_SAME_AS_SAMPLE0)
853                         continue;
854                 byte_offset = di->dec_channelmap[i] / 8;
855                 bit_offset = di->dec_channelmap[i] % 8;
856                 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
857                 di->old_pins_array->data[i] = sample;
858         }
859 }
860
861 static gboolean term_matches(const struct srd_decoder_inst *di,
862                 struct srd_term *term, const uint8_t *sample_pos)
863 {
864         uint8_t old_sample, sample;
865         int byte_offset, bit_offset, ch;
866
867         /* Caller ensures di, di->dec_channelmap, term, sample_pos != NULL. */
868
869         if (term->type == SRD_TERM_SKIP)
870                 return sample_matches(0, 0, term);
871
872         ch = term->channel;
873         byte_offset = di->dec_channelmap[ch] / 8;
874         bit_offset = di->dec_channelmap[ch] % 8;
875         sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
876         old_sample = di->old_pins_array->data[ch];
877
878         return sample_matches(old_sample, sample, term);
879 }
880
881 static gboolean all_terms_match(const struct srd_decoder_inst *di,
882                 const GSList *cond, const uint8_t *sample_pos)
883 {
884         const GSList *l;
885         struct srd_term *term;
886
887         /* Caller ensures di, cond, sample_pos != NULL. */
888
889         for (l = cond; l; l = l->next) {
890                 term = l->data;
891                 if (!term_matches(di, term, sample_pos))
892                         return FALSE;
893         }
894
895         return TRUE;
896 }
897
898 static gboolean at_least_one_condition_matched(
899                 const struct srd_decoder_inst *di, unsigned int num_conditions)
900 {
901         unsigned int i;
902
903         /* Caller ensures di != NULL. */
904
905         for (i = 0; i < num_conditions; i++) {
906                 if (di->match_array->data[i])
907                         return TRUE;
908         }
909
910         return FALSE;
911 }
912
913 static gboolean find_match(struct srd_decoder_inst *di)
914 {
915         uint64_t i, j, num_samples_to_process;
916         GSList *l, *cond;
917         const uint8_t *sample_pos;
918         unsigned int num_conditions;
919
920         /* Caller ensures di != NULL. */
921
922         /* Check whether the condition list is NULL/empty. */
923         if (!di->condition_list) {
924                 srd_dbg("NULL/empty condition list, automatic match.");
925                 return TRUE;
926         }
927
928         /* Check whether we have any non-NULL conditions. */
929         if (!have_non_null_conds(di)) {
930                 srd_dbg("Only NULL conditions in list, automatic match.");
931                 return TRUE;
932         }
933
934         num_samples_to_process = di->abs_end_samplenum - di->abs_cur_samplenum;
935         num_conditions = g_slist_length(di->condition_list);
936
937         /* di->match_array is NULL here. Create a new GArray. */
938         di->match_array = g_array_sized_new(FALSE, TRUE, sizeof(gboolean), num_conditions);
939         g_array_set_size(di->match_array, num_conditions);
940
941         /* Sample 0: Set di->old_pins_array for SRD_INITIAL_PIN_SAME_AS_SAMPLE0 pins. */
942         if (di->abs_cur_samplenum == 0)
943                 update_old_pins_array_initial_pins(di);
944
945         for (i = 0; i < num_samples_to_process; i++, (di->abs_cur_samplenum)++) {
946
947                 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
948
949                 /* Check whether the current sample matches at least one of the conditions (logical OR). */
950                 /* IMPORTANT: We need to check all conditions, even if there was a match already! */
951                 for (l = di->condition_list, j = 0; l; l = l->next, j++) {
952                         cond = l->data;
953                         if (!cond)
954                                 continue;
955                         /* All terms in 'cond' must match (logical AND). */
956                         di->match_array->data[j] = all_terms_match(di, cond, sample_pos);
957                 }
958
959                 update_old_pins_array(di, sample_pos);
960
961                 /* If at least one condition matched we're done. */
962                 if (at_least_one_condition_matched(di, num_conditions))
963                         return TRUE;
964         }
965
966         return FALSE;
967 }
968
969 /**
970  * Process available samples and check if they match the defined conditions.
971  *
972  * This function returns if there is an error, or when a match is found, or
973  * when all samples have been processed (whether a match was found or not).
974  * This function immediately terminates when the decoder's wait() method
975  * invocation shall get terminated.
976  *
977  * @param di The decoder instance to use. Must not be NULL.
978  * @param found_match Will be set to TRUE if at least one condition matched,
979  *                    FALSE otherwise. Must not be NULL.
980  *
981  * @retval SRD_OK No errors occured, see found_match for the result.
982  * @retval SRD_ERR_ARG Invalid arguments.
983  *
984  * @private
985  */
986 SRD_PRIV int process_samples_until_condition_match(struct srd_decoder_inst *di, gboolean *found_match)
987 {
988         if (!di || !found_match)
989                 return SRD_ERR_ARG;
990
991         *found_match = FALSE;
992         if (di->want_wait_terminate)
993                 return SRD_OK;
994
995         /* Check if any of the current condition(s) match. */
996         while (TRUE) {
997                 /* Feed the (next chunk of the) buffer to find_match(). */
998                 *found_match = find_match(di);
999
1000                 /* Did we handle all samples yet? */
1001                 if (di->abs_cur_samplenum >= di->abs_end_samplenum) {
1002                         srd_dbg("Done, handled all samples (abs cur %" PRIu64
1003                                 " / abs end %" PRIu64 ").",
1004                                 di->abs_cur_samplenum, di->abs_end_samplenum);
1005                         return SRD_OK;
1006                 }
1007
1008                 /* If we didn't find a match, continue looking. */
1009                 if (!(*found_match))
1010                         continue;
1011
1012                 /* At least one condition matched, return. */
1013                 return SRD_OK;
1014         }
1015
1016         return SRD_OK;
1017 }
1018
1019 /**
1020  * Worker thread (per PD-stack).
1021  *
1022  * @param data Pointer to the lowest-level PD's device instance.
1023  *             Must not be NULL.
1024  *
1025  * @return NULL if there was an error.
1026  */
1027 static gpointer di_thread(gpointer data)
1028 {
1029         PyObject *py_res;
1030         struct srd_decoder_inst *di;
1031         int wanted_term;
1032         PyGILState_STATE gstate;
1033
1034         if (!data)
1035                 return NULL;
1036
1037         di = data;
1038
1039         srd_dbg("%s: Starting thread routine for decoder.", di->inst_id);
1040
1041         gstate = PyGILState_Ensure();
1042
1043         /*
1044          * Call self.decode(). Only returns if the PD throws an exception.
1045          * "Regular" termination of the decode() method is not expected.
1046          */
1047         Py_IncRef(di->py_inst);
1048         srd_dbg("%s: Calling decode().", di->inst_id);
1049         py_res = PyObject_CallMethod(di->py_inst, "decode", NULL);
1050         srd_dbg("%s: decode() terminated.", di->inst_id);
1051
1052         if (!py_res)
1053                 di->decoder_state = SRD_ERR;
1054
1055         /*
1056          * Make sure to unblock potentially pending srd_inst_decode()
1057          * calls in application threads after the decode() method might
1058          * have terminated, while it neither has processed sample data
1059          * nor has terminated upon request. This happens e.g. when "need
1060          * a samplerate to decode" exception is thrown.
1061          */
1062         g_mutex_lock(&di->data_mutex);
1063         wanted_term = di->want_wait_terminate;
1064         di->want_wait_terminate = TRUE;
1065         di->handled_all_samples = TRUE;
1066         g_cond_signal(&di->handled_all_samples_cond);
1067         g_mutex_unlock(&di->data_mutex);
1068
1069         /*
1070          * Check for the termination cause of the decode() method.
1071          * Though this is mostly for information.
1072          */
1073         if (!py_res && wanted_term) {
1074                 /*
1075                  * Silently ignore errors upon return from decode() calls
1076                  * when termination was requested. Terminate the thread
1077                  * which executed this instance's decode() logic.
1078                  */
1079                 srd_dbg("%s: Thread done (!res, want_term).", di->inst_id);
1080                 PyErr_Clear();
1081                 PyGILState_Release(gstate);
1082                 return NULL;
1083         }
1084         if (!py_res) {
1085                 /*
1086                  * The decode() invocation terminated unexpectedly. Have
1087                  * the back trace printed, and terminate the thread which
1088                  * executed the decode() method.
1089                  */
1090                 srd_dbg("%s: decode() terminated unrequested.", di->inst_id);
1091                 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
1092                 srd_dbg("%s: Thread done (!res, !want_term).", di->inst_id);
1093                 PyGILState_Release(gstate);
1094                 return NULL;
1095         }
1096
1097         /*
1098          * TODO: By design the decode() method is not supposed to terminate.
1099          * Nevertheless we have the thread joined, and srd backend calls to
1100          * decode() will re-start another thread transparently.
1101          */
1102         srd_dbg("%s: decode() terminated (req %d).", di->inst_id, wanted_term);
1103         Py_DecRef(py_res);
1104         PyErr_Clear();
1105
1106         PyGILState_Release(gstate);
1107
1108         srd_dbg("%s: Thread done (with res).", di->inst_id);
1109
1110         return NULL;
1111 }
1112
1113 /**
1114  * Decode a chunk of samples.
1115  *
1116  * The calls to this function must provide the samples that shall be
1117  * used by the protocol decoder
1118  *  - in the correct order ([...]5, 6, 4, 7, 8[...] is a bug),
1119  *  - starting from sample zero (2, 3, 4, 5, 6[...] is a bug),
1120  *  - consecutively, with no gaps (0, 1, 2, 4, 5[...] is a bug).
1121  *
1122  * The start- and end-sample numbers are absolute sample numbers (relative
1123  * to the start of the whole capture/file/stream), i.e. they are not relative
1124  * sample numbers within the chunk specified by 'inbuf' and 'inbuflen'.
1125  *
1126  * Correct example (4096 samples total, 4 chunks @ 1024 samples each):
1127  *   srd_inst_decode(di, 0,    1024, inbuf, 1024, 1);
1128  *   srd_inst_decode(di, 1024, 2048, inbuf, 1024, 1);
1129  *   srd_inst_decode(di, 2048, 3072, inbuf, 1024, 1);
1130  *   srd_inst_decode(di, 3072, 4096, inbuf, 1024, 1);
1131  *
1132  * The chunk size ('inbuflen') can be arbitrary and can differ between calls.
1133  *
1134  * Correct example (4096 samples total, 7 chunks @ various samples each):
1135  *   srd_inst_decode(di, 0,    1024, inbuf, 1024, 1);
1136  *   srd_inst_decode(di, 1024, 1124, inbuf,  100, 1);
1137  *   srd_inst_decode(di, 1124, 1424, inbuf,  300, 1);
1138  *   srd_inst_decode(di, 1424, 1643, inbuf,  219, 1);
1139  *   srd_inst_decode(di, 1643, 2048, inbuf,  405, 1);
1140  *   srd_inst_decode(di, 2048, 3072, inbuf, 1024, 1);
1141  *   srd_inst_decode(di, 3072, 4096, inbuf, 1024, 1);
1142  *
1143  * INCORRECT example (4096 samples total, 4 chunks @ 1024 samples each, but
1144  * the start- and end-samplenumbers are not absolute):
1145  *   srd_inst_decode(di, 0,    1024, inbuf, 1024, 1);
1146  *   srd_inst_decode(di, 0,    1024, inbuf, 1024, 1);
1147  *   srd_inst_decode(di, 0,    1024, inbuf, 1024, 1);
1148  *   srd_inst_decode(di, 0,    1024, inbuf, 1024, 1);
1149  *
1150  * @param di The decoder instance to call. Must not be NULL.
1151  * @param abs_start_samplenum The absolute starting sample number for the
1152  *              buffer's sample set, relative to the start of capture.
1153  * @param abs_end_samplenum The absolute ending sample number for the
1154  *              buffer's sample set, relative to the start of capture.
1155  * @param inbuf The buffer to decode. Must not be NULL.
1156  * @param inbuflen Length of the buffer. Must be > 0.
1157  * @param unitsize The number of bytes per sample. Must be > 0.
1158  *
1159  * @return SRD_OK upon success, a (negative) error code otherwise.
1160  *
1161  * @private
1162  */
1163 SRD_PRIV int srd_inst_decode(struct srd_decoder_inst *di,
1164                 uint64_t abs_start_samplenum, uint64_t abs_end_samplenum,
1165                 const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
1166 {
1167         /* Return an error upon unusable input. */
1168         if (!di) {
1169                 srd_dbg("empty decoder instance");
1170                 return SRD_ERR_ARG;
1171         }
1172         if (!inbuf) {
1173                 srd_dbg("NULL buffer pointer");
1174                 return SRD_ERR_ARG;
1175         }
1176         if (inbuflen == 0) {
1177                 srd_dbg("empty buffer");
1178                 return SRD_ERR_ARG;
1179         }
1180         if (unitsize == 0) {
1181                 srd_dbg("unitsize 0");
1182                 return SRD_ERR_ARG;
1183         }
1184
1185         if (abs_start_samplenum != di->abs_cur_samplenum ||
1186             abs_end_samplenum < abs_start_samplenum) {
1187                 srd_dbg("Incorrect sample numbers: start=%" PRIu64 ", cur=%"
1188                         PRIu64 ", end=%" PRIu64 ".", abs_start_samplenum,
1189                         di->abs_cur_samplenum, abs_end_samplenum);
1190                 return SRD_ERR_ARG;
1191         }
1192
1193         di->data_unitsize = unitsize;
1194
1195         srd_dbg("Decoding: abs start sample %" PRIu64 ", abs end sample %"
1196                 PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = "
1197                 "%d), instance %s.", abs_start_samplenum, abs_end_samplenum,
1198                 abs_end_samplenum - abs_start_samplenum, inbuflen, di->data_unitsize,
1199                 di->inst_id);
1200
1201         /* If this is the first call, start the worker thread. */
1202         if (!di->thread_handle) {
1203                 srd_dbg("No worker thread for this decoder stack "
1204                         "exists yet, creating one: %s.", di->inst_id);
1205                 di->thread_handle = g_thread_new(di->inst_id,
1206                                                  di_thread, di);
1207         }
1208
1209         /* Push the new sample chunk to the worker thread. */
1210         g_mutex_lock(&di->data_mutex);
1211         di->abs_start_samplenum = abs_start_samplenum;
1212         di->abs_end_samplenum = abs_end_samplenum;
1213         di->inbuf = inbuf;
1214         di->inbuflen = inbuflen;
1215         di->got_new_samples = TRUE;
1216         di->handled_all_samples = FALSE;
1217
1218         /* Signal the thread that we have new data. */
1219         g_cond_signal(&di->got_new_samples_cond);
1220         g_mutex_unlock(&di->data_mutex);
1221
1222         /* When all samples in this chunk were handled, return. */
1223         g_mutex_lock(&di->data_mutex);
1224         while (!di->handled_all_samples && !di->want_wait_terminate)
1225                 g_cond_wait(&di->handled_all_samples_cond, &di->data_mutex);
1226         g_mutex_unlock(&di->data_mutex);
1227
1228         if (di->want_wait_terminate)
1229                 return SRD_ERR_TERM_REQ;
1230
1231         return SRD_OK;
1232 }
1233
1234 /**
1235  * Terminate current decoder work, prepare for re-use on new input data.
1236  *
1237  * Terminates all decoder operations in the specified decoder instance
1238  * and the instances stacked on top of it. Resets internal state such
1239  * that the previously constructed stack can process new input data that
1240  * is not related to previously processed input data. This avoids the
1241  * expensive and complex re-construction of decoder stacks.
1242  *
1243  * Callers are expected to follow up with start, metadata, and decode
1244  * calls like they would for newly constructed decoder stacks.
1245  *
1246  * @param di The decoder instance to call. Must not be NULL.
1247  *
1248  * @return SRD_OK upon success, a (negative) error code otherwise.
1249  *
1250  * @private
1251  */
1252 SRD_PRIV int srd_inst_terminate_reset(struct srd_decoder_inst *di)
1253 {
1254         PyGILState_STATE gstate;
1255         PyObject *py_ret;
1256         GSList *l;
1257         int ret;
1258
1259         if (!di)
1260                 return SRD_ERR_ARG;
1261
1262         /*
1263          * Request termination and wait for previously initiated
1264          * background operation to finish. Reset internal state, but
1265          * do not start releasing resources yet. This shall result in
1266          * decoders' state just like after creation. This block handles
1267          * the C language library side.
1268          */
1269         srd_dbg("Terminating instance %s", di->inst_id);
1270         srd_inst_join_decode_thread(di);
1271         srd_inst_reset_state(di);
1272
1273         /*
1274          * Have the Python side's .reset() method executed (if the PD
1275          * implements it). It's assumed that .reset() assigns variables
1276          * very much like __init__() used to do in the past. Thus memory
1277          * that was allocated in previous calls gets released by Python
1278          * as it's not referenced any longer.
1279          */
1280         gstate = PyGILState_Ensure();
1281         if (PyObject_HasAttrString(di->py_inst, "reset")) {
1282                 srd_dbg("Calling reset() of instance %s", di->inst_id);
1283                 py_ret = PyObject_CallMethod(di->py_inst, "reset", NULL);
1284                 Py_XDECREF(py_ret);
1285         }
1286         PyGILState_Release(gstate);
1287
1288         /* Pass the "restart" request to all stacked decoders. */
1289         for (l = di->next_di; l; l = l->next) {
1290                 ret = srd_inst_terminate_reset(l->data);
1291                 if (ret != SRD_OK)
1292                         return ret;
1293         }
1294
1295         return di->decoder_state;
1296 }
1297
1298 /** @private */
1299 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
1300 {
1301         GSList *l;
1302         struct srd_pd_output *pdo;
1303         PyGILState_STATE gstate;
1304
1305         srd_dbg("Freeing instance %s.", di->inst_id);
1306
1307         srd_inst_join_decode_thread(di);
1308
1309         srd_inst_reset_state(di);
1310
1311         gstate = PyGILState_Ensure();
1312         Py_DecRef(di->py_inst);
1313         PyGILState_Release(gstate);
1314
1315         g_free(di->inst_id);
1316         g_free(di->dec_channelmap);
1317         g_free(di->channel_samples);
1318         g_slist_free(di->next_di);
1319         for (l = di->pd_output; l; l = l->next) {
1320                 pdo = l->data;
1321                 g_free(pdo->proto_id);
1322                 g_free(pdo);
1323         }
1324         g_slist_free(di->pd_output);
1325         g_free(di);
1326 }
1327
1328 /** @private */
1329 SRD_PRIV void srd_inst_free_all(struct srd_session *sess)
1330 {
1331         if (!sess)
1332                 return;
1333
1334         g_slist_free_full(sess->di_list, (GDestroyNotify)srd_inst_free);
1335 }
1336
1337 /** @} */