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