]> sigrok.org Git - libsigrokdecode.git/blob - controller.c
Move session-specific functionality into session.c
[libsigrokdecode.git] / controller.c
1 /*
2  * This file is part of the libsigrokdecode project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "libsigrokdecode-internal.h"
23 #include "config.h"
24 #include <glib.h>
25 #include <inttypes.h>
26 #include <stdlib.h>
27 #include <stdint.h>
28
29 /**
30  * @mainpage libsigrokdecode API
31  *
32  * @section sec_intro Introduction
33  *
34  * The <a href="http://sigrok.org">sigrok</a> project aims at creating a
35  * portable, cross-platform, Free/Libre/Open-Source signal analysis software
36  * suite that supports various device types (such as logic analyzers,
37  * oscilloscopes, multimeters, and more).
38  *
39  * <a href="http://sigrok.org/wiki/Libsigrokdecode">libsigrokdecode</a> is a
40  * shared library written in C which provides the basic API for (streaming)
41  * protocol decoding functionality.
42  *
43  * The <a href="http://sigrok.org/wiki/Protocol_decoders">protocol decoders</a>
44  * are written in Python (>= 3.0).
45  *
46  * @section sec_api API reference
47  *
48  * See the "Modules" page for an introduction to various libsigrokdecode
49  * related topics and the detailed API documentation of the respective
50  * functions.
51  *
52  * You can also browse the API documentation by file, or review all
53  * data structures.
54  *
55  * @section sec_mailinglists Mailing lists
56  *
57  * There are two mailing lists for sigrok/libsigrokdecode: <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-devel">sigrok-devel</a> and <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-commits">sigrok-commits</a>.
58  *
59  * @section sec_irc IRC
60  *
61  * You can find the sigrok developers in the
62  * <a href="irc://chat.freenode.net/sigrok">\#sigrok</a>
63  * IRC channel on Freenode.
64  *
65  * @section sec_website Website
66  *
67  * <a href="http://sigrok.org/wiki/Libsigrokdecode">sigrok.org/wiki/Libsigrokdecode</a>
68  */
69
70 /**
71  * @file
72  *
73  * Initializing and shutting down libsigrokdecode.
74  */
75
76 /**
77  * @defgroup grp_init Initialization
78  *
79  * Initializing and shutting down libsigrokdecode.
80  *
81  * Before using any of the libsigrokdecode functionality, srd_init() must
82  * be called to initialize the library.
83  *
84  * When libsigrokdecode functionality is no longer needed, srd_exit() should
85  * be called.
86  *
87  * @{
88  */
89
90 /** @cond PRIVATE */
91
92 extern GSList *sessions;
93 extern int max_session_id;
94
95 /* decoder.c */
96 extern SRD_PRIV GSList *pd_list;
97
98 /* module_sigrokdecode.c */
99 extern PyMODINIT_FUNC PyInit_sigrokdecode(void);
100
101 /* type_logic.c */
102 extern SRD_PRIV PyTypeObject srd_logic_type;
103
104 /** @endcond */
105
106 /**
107  * Initialize libsigrokdecode.
108  *
109  * This initializes the Python interpreter, and creates and initializes
110  * a "sigrokdecode" Python module.
111  *
112  * Then, it searches for sigrok protocol decoders in the "decoders"
113  * subdirectory of the the libsigrokdecode installation directory.
114  * All decoders that are found are loaded into memory and added to an
115  * internal list of decoders, which can be queried via srd_decoder_list().
116  *
117  * The caller is responsible for calling the clean-up function srd_exit(),
118  * which will properly shut down libsigrokdecode and free its allocated memory.
119  *
120  * Multiple calls to srd_init(), without calling srd_exit() in between,
121  * are not allowed.
122  *
123  * @param path Path to an extra directory containing protocol decoders
124  *             which will be added to the Python sys.path. May be NULL.
125  *
126  * @return SRD_OK upon success, a (negative) error code otherwise.
127  *         Upon Python errors, SRD_ERR_PYTHON is returned. If the decoders
128  *         directory cannot be accessed, SRD_ERR_DECODERS_DIR is returned.
129  *         If not enough memory could be allocated, SRD_ERR_MALLOC is returned.
130  *
131  * @since 0.1.0
132  */
133 SRD_API int srd_init(const char *path)
134 {
135         int ret;
136         char *env_path;
137
138         if (max_session_id != -1) {
139                 srd_err("libsigrokdecode is already initialized.");
140                 return SRD_ERR;
141         }
142
143         srd_dbg("Initializing libsigrokdecode.");
144
145         /* Add our own module to the list of built-in modules. */
146         PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
147
148         /* Initialize the Python interpreter. */
149         Py_Initialize();
150
151         /* Installed decoders. */
152         if ((ret = srd_decoder_searchpath_add(DECODERS_DIR)) != SRD_OK) {
153                 Py_Finalize();
154                 return ret;
155         }
156
157         /* Path specified by the user. */
158         if (path) {
159                 if ((ret = srd_decoder_searchpath_add(path)) != SRD_OK) {
160                         Py_Finalize();
161                         return ret;
162                 }
163         }
164
165         /* Environment variable overrides everything, for debugging. */
166         if ((env_path = getenv("SIGROKDECODE_DIR"))) {
167                 if ((ret = srd_decoder_searchpath_add(env_path)) != SRD_OK) {
168                         Py_Finalize();
169                         return ret;
170                 }
171         }
172
173         max_session_id = 0;
174
175         return SRD_OK;
176 }
177
178 /**
179  * Shutdown libsigrokdecode.
180  *
181  * This frees all the memory allocated for protocol decoders and shuts down
182  * the Python interpreter.
183  *
184  * This function should only be called if there was a (successful!) invocation
185  * of srd_init() before. Calling this function multiple times in a row, without
186  * any successful srd_init() calls in between, is not allowed.
187  *
188  * @return SRD_OK upon success, a (negative) error code otherwise.
189  *
190  * @since 0.1.0
191  */
192 SRD_API int srd_exit(void)
193 {
194         GSList *l;
195
196         srd_dbg("Exiting libsigrokdecode.");
197
198         for (l = sessions; l; l = l->next)
199                 srd_session_destroy((struct srd_session *)l->data);
200
201         srd_decoder_unload_all();
202         g_slist_free(pd_list);
203         pd_list = NULL;
204
205         /* Py_Finalize() returns void, any finalization errors are ignored. */
206         Py_Finalize();
207
208         max_session_id = -1;
209
210         return SRD_OK;
211 }
212
213 /**
214  * Add an additional search directory for the protocol decoders.
215  *
216  * The specified directory is prepended (not appended!) to Python's sys.path,
217  * in order to search for sigrok protocol decoders in the specified
218  * directories first, and in the generic Python module directories (and in
219  * the current working directory) last. This avoids conflicts if there are
220  * Python modules which have the same name as a sigrok protocol decoder in
221  * sys.path or in the current working directory.
222  *
223  * @param path Path to the directory containing protocol decoders which shall
224  *             be added to the Python sys.path, or NULL.
225  *
226  * @return SRD_OK upon success, a (negative) error code otherwise.
227  *
228  * @private
229  *
230  * @since 0.1.0
231  */
232 SRD_PRIV int srd_decoder_searchpath_add(const char *path)
233 {
234         PyObject *py_cur_path, *py_item;
235         GString *new_path;
236         int wc_len, i;
237         wchar_t *wc_new_path;
238         char *item;
239
240         srd_dbg("Adding '%s' to module path.", path);
241
242         new_path = g_string_sized_new(256);
243         g_string_assign(new_path, path);
244         py_cur_path = PySys_GetObject("path");
245         for (i = 0; i < PyList_Size(py_cur_path); i++) {
246                 g_string_append(new_path, G_SEARCHPATH_SEPARATOR_S);
247                 py_item = PyList_GetItem(py_cur_path, i);
248                 if (!PyUnicode_Check(py_item))
249                         /* Shouldn't happen. */
250                         continue;
251                 if (py_str_as_str(py_item, &item) != SRD_OK)
252                         continue;
253                 g_string_append(new_path, item);
254                 g_free(item);
255         }
256
257         /* Convert to wide chars. */
258         wc_len = sizeof(wchar_t) * (new_path->len + 1);
259         if (!(wc_new_path = g_try_malloc(wc_len))) {
260                 srd_dbg("malloc failed");
261                 return SRD_ERR_MALLOC;
262         }
263         mbstowcs(wc_new_path, new_path->str, wc_len);
264         PySys_SetPath(wc_new_path);
265         g_string_free(new_path, TRUE);
266         g_free(wc_new_path);
267
268         return SRD_OK;
269 }
270
271 /** @} */
272
273 /**
274  * @defgroup grp_instances Decoder instances
275  *
276  * Decoder instance handling.
277  *
278  * @{
279  */
280
281 /**
282  * Set one or more options in a decoder instance.
283  *
284  * Handled options are removed from the hash.
285  *
286  * @param di Decoder instance.
287  * @param options A GHashTable of options to set.
288  *
289  * @return SRD_OK upon success, a (negative) error code otherwise.
290  *
291  * @since 0.1.0
292  */
293 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
294                 GHashTable *options)
295 {
296         PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
297         PyObject *py_optlist, *py_classval;
298         Py_UNICODE *py_ustr;
299         GVariant *value;
300         unsigned long long int val_ull;
301         gint64 val_int;
302         int num_optkeys, ret, size, i;
303         const char *val_str;
304         char *dbg, *key;
305
306         if (!di) {
307                 srd_err("Invalid decoder instance.");
308                 return SRD_ERR_ARG;
309         }
310
311         if (!options) {
312                 srd_err("Invalid options GHashTable.");
313                 return SRD_ERR_ARG;
314         }
315
316         if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
317                 /* Decoder has no options. */
318                 if (g_hash_table_size(options) == 0) {
319                         /* No options provided. */
320                         return SRD_OK;
321                 } else {
322                         srd_err("Protocol decoder has no options.");
323                         return SRD_ERR_ARG;
324                 }
325                 return SRD_OK;
326         }
327
328         ret = SRD_ERR_PYTHON;
329         key = NULL;
330         py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
331         py_optlist = py_classval = NULL;
332         py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");
333
334         /* All of these are synthesized objects, so they're good. */
335         py_dec_optkeys = PyDict_Keys(py_dec_options);
336         num_optkeys = PyList_Size(py_dec_optkeys);
337
338         /*
339          * The 'options' dictionary is a class variable, but we need to
340          * change it. Changing it directly will affect the entire class,
341          * so we need to create a new object for it, and populate that
342          * instead.
343          */
344         if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
345                 goto err_out;
346         Py_DECREF(py_di_options);
347         py_di_options = PyDict_New();
348         PyObject_SetAttrString(di->py_inst, "options", py_di_options);
349         for (i = 0; i < num_optkeys; i++) {
350                 /* Get the default class value for this option. */
351                 py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
352                 if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
353                         goto err_out;
354                 if (!(py_classval = PyList_GetItem(py_optlist, 1)))
355                         goto err_out;
356                 if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) {
357                         srd_err("Options of type %s are not yet supported.",
358                                 Py_TYPE(py_classval)->tp_name);
359                         goto err_out;
360                 }
361
362                 if ((value = g_hash_table_lookup(options, key))) {
363                         dbg = g_variant_print(value, TRUE);
364                         srd_dbg("got option '%s' = %s", key, dbg);
365                         g_free(dbg);
366                         /* An override for this option was provided. */
367                         if (PyUnicode_Check(py_classval)) {
368                                 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
369                                         srd_err("Option '%s' requires a string value.", key);
370                                         goto err_out;
371                                 }
372                                 val_str = g_variant_get_string(value, NULL);
373                                 if (!(py_optval = PyUnicode_FromString(val_str))) {
374                                         /* Some UTF-8 encoding error. */
375                                         PyErr_Clear();
376                                         srd_err("Option '%s' requires a UTF-8 string value.", key);
377                                         goto err_out;
378                                 }
379                         } else if (PyLong_Check(py_classval)) {
380                                 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
381                                         srd_err("Option '%s' requires an integer value.", key);
382                                         goto err_out;
383                                 }
384                                 val_int = g_variant_get_int64(value);
385                                 if (!(py_optval = PyLong_FromLong(val_int))) {
386                                         /* ValueError Exception */
387                                         PyErr_Clear();
388                                         srd_err("Option '%s' has invalid integer value.", key);
389                                         goto err_out;
390                                 }
391                         }
392                         g_hash_table_remove(options, key);
393                 } else {
394                         /* Use the class default for this option. */
395                         if (PyUnicode_Check(py_classval)) {
396                                 /* Make a brand new copy of the string. */
397                                 py_ustr = PyUnicode_AS_UNICODE(py_classval);
398                                 size = PyUnicode_GET_SIZE(py_classval);
399                                 py_optval = PyUnicode_FromUnicode(py_ustr, size);
400                         } else if (PyLong_Check(py_classval)) {
401                                 /* Make a brand new copy of the integer. */
402                                 val_ull = PyLong_AsUnsignedLongLong(py_classval);
403                                 if (val_ull == (unsigned long long)-1) {
404                                         /* OverFlowError exception */
405                                         PyErr_Clear();
406                                         srd_err("Invalid integer value for %s: "
407                                                 "expected integer.", key);
408                                         goto err_out;
409                                 }
410                                 if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
411                                         goto err_out;
412                         }
413                 }
414
415                 /*
416                  * If we got here, py_optval holds a known good new reference
417                  * to the instance option to set.
418                  */
419                 if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
420                         goto err_out;
421                 g_free(key);
422                 key = NULL;
423         }
424
425         ret = SRD_OK;
426
427 err_out:
428         Py_XDECREF(py_di_options);
429         Py_XDECREF(py_dec_optkeys);
430         Py_XDECREF(py_dec_options);
431         g_free(key);
432         if (PyErr_Occurred()) {
433                 srd_exception_catch("Stray exception in srd_inst_option_set().");
434                 ret = SRD_ERR_PYTHON;
435         }
436
437         return ret;
438 }
439
440 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_probe_set_all() */
441 static gint compare_probe_id(const struct srd_probe *a, const char *probe_id)
442 {
443         return strcmp(a->id, probe_id);
444 }
445
446 /**
447  * Set all probes in a decoder instance.
448  *
449  * This function sets _all_ probes for the specified decoder instance, i.e.,
450  * it overwrites any probes that were already defined (if any).
451  *
452  * @param di Decoder instance.
453  * @param new_probes A GHashTable of probes to set. Key is probe name, value is
454  *                   the probe number. Samples passed to this instance will be
455  *                   arranged in this order.
456  *
457  * @return SRD_OK upon success, a (negative) error code otherwise.
458  *
459  * @since 0.1.0
460  */
461 SRD_API int srd_inst_probe_set_all(struct srd_decoder_inst *di,
462                 GHashTable *new_probes)
463 {
464         GVariant *probe_val;
465         GList *l;
466         GSList *sl;
467         struct srd_probe *p;
468         int *new_probemap, new_probenum, num_required_probes, num_probes, i;
469         char *probe_id;
470
471         srd_dbg("set probes called for instance %s with list of %d probes",
472                 di->inst_id, g_hash_table_size(new_probes));
473
474         if (g_hash_table_size(new_probes) == 0)
475                 /* No probes provided. */
476                 return SRD_OK;
477
478         if (di->dec_num_probes == 0) {
479                 /* Decoder has no probes. */
480                 srd_err("Protocol decoder %s has no probes to define.",
481                         di->decoder->name);
482                 return SRD_ERR_ARG;
483         }
484
485         new_probemap = NULL;
486
487         if (!(new_probemap = g_try_malloc(sizeof(int) * di->dec_num_probes))) {
488                 srd_err("Failed to g_malloc() new probe map.");
489                 return SRD_ERR_MALLOC;
490         }
491
492         /*
493          * For now, map all indexes to probe -1 (can be overridden later).
494          * This -1 is interpreted as an unspecified probe later.
495          */
496         for (i = 0; i < di->dec_num_probes; i++)
497                 new_probemap[i] = -1;
498
499         num_probes = 0;
500         for (l = g_hash_table_get_keys(new_probes); l; l = l->next) {
501                 probe_id = l->data;
502                 probe_val = g_hash_table_lookup(new_probes, probe_id);
503                 if (!g_variant_is_of_type(probe_val, G_VARIANT_TYPE_INT32)) {
504                         /* Probe name was specified without a value. */
505                         srd_err("No probe number was specified for %s.",
506                                         probe_id);
507                         g_free(new_probemap);
508                         return SRD_ERR_ARG;
509                 }
510                 new_probenum = g_variant_get_int32(probe_val);
511                 if (!(sl = g_slist_find_custom(di->decoder->probes, probe_id,
512                                 (GCompareFunc)compare_probe_id))) {
513                         /* Fall back on optional probes. */
514                         if (!(sl = g_slist_find_custom(di->decoder->opt_probes,
515                              probe_id, (GCompareFunc) compare_probe_id))) {
516                                 srd_err("Protocol decoder %s has no probe "
517                                                 "'%s'.", di->decoder->name, probe_id);
518                                 g_free(new_probemap);
519                                 return SRD_ERR_ARG;
520                         }
521                 }
522                 p = sl->data;
523                 new_probemap[p->order] = new_probenum;
524                 srd_dbg("Setting probe mapping: %s (index %d) = probe %d.",
525                         p->id, p->order, new_probenum);
526                 num_probes++;
527         }
528         di->data_unitsize = (num_probes + 7) / 8;
529
530         srd_dbg("Final probe map:");
531         num_required_probes = g_slist_length(di->decoder->probes);
532         for (i = 0; i < di->dec_num_probes; i++) {
533                 srd_dbg(" - index %d = probe %d (%s)", i, new_probemap[i],
534                         (i < num_required_probes) ? "required" : "optional");
535         }
536
537         g_free(di->dec_probemap);
538         di->dec_probemap = new_probemap;
539
540         return SRD_OK;
541 }
542
543 /**
544  * Create a new protocol decoder instance.
545  *
546  * @param sess The session holding the protocol decoder instance.
547  * @param decoder_id Decoder 'id' field.
548  * @param options GHashtable of options which override the defaults set in
549  *                the decoder class. May be NULL.
550  *
551  * @return Pointer to a newly allocated struct srd_decoder_inst, or
552  *         NULL in case of failure.
553  *
554  * @since 0.3.0
555  */
556 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
557                 const char *decoder_id, GHashTable *options)
558 {
559         int i;
560         struct srd_decoder *dec;
561         struct srd_decoder_inst *di;
562         char *inst_id;
563
564         srd_dbg("Creating new %s instance.", decoder_id);
565
566         if (session_is_valid(sess) != SRD_OK) {
567                 srd_err("Invalid session.");
568                 return NULL;
569         }
570
571         if (!(dec = srd_decoder_get_by_id(decoder_id))) {
572                 srd_err("Protocol decoder %s not found.", decoder_id);
573                 return NULL;
574         }
575
576         if (!(di = g_try_malloc0(sizeof(struct srd_decoder_inst)))) {
577                 srd_err("Failed to g_malloc() instance.");
578                 return NULL;
579         }
580
581         di->decoder = dec;
582         di->sess = sess;
583         if (options) {
584                 inst_id = g_hash_table_lookup(options, "id");
585                 di->inst_id = g_strdup(inst_id ? inst_id : decoder_id);
586                 g_hash_table_remove(options, "id");
587         } else
588                 di->inst_id = g_strdup(decoder_id);
589
590         /*
591          * Prepare a default probe map, where samples come in the
592          * order in which the decoder class defined them.
593          */
594         di->dec_num_probes = g_slist_length(di->decoder->probes) +
595                         g_slist_length(di->decoder->opt_probes);
596         if (di->dec_num_probes) {
597                 if (!(di->dec_probemap =
598                                 g_try_malloc(sizeof(int) * di->dec_num_probes))) {
599                         srd_err("Failed to g_malloc() probe map.");
600                         g_free(di);
601                         return NULL;
602                 }
603                 for (i = 0; i < di->dec_num_probes; i++)
604                         di->dec_probemap[i] = i;
605         }
606         di->data_unitsize = (di->dec_num_probes + 7) / 8;
607
608         /* Create a new instance of this decoder class. */
609         if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
610                 if (PyErr_Occurred())
611                         srd_exception_catch("failed to create %s instance: ",
612                                         decoder_id);
613                 g_free(di->dec_probemap);
614                 g_free(di);
615                 return NULL;
616         }
617
618         if (options && srd_inst_option_set(di, options) != SRD_OK) {
619                 g_free(di->dec_probemap);
620                 g_free(di);
621                 return NULL;
622         }
623
624         /* Instance takes input from a frontend by default. */
625         sess->di_list = g_slist_append(sess->di_list, di);
626
627         return di;
628 }
629
630 /**
631  * Stack a decoder instance on top of another.
632  *
633  * @param sess The session holding the protocol decoder instances.
634  * @param di_from The instance to move.
635  * @param di_to The instance on top of which di_from will be stacked.
636  *
637  * @return SRD_OK upon success, a (negative) error code otherwise.
638  *
639  * @since 0.3.0
640  */
641 SRD_API int srd_inst_stack(struct srd_session *sess,
642                 struct srd_decoder_inst *di_from, struct srd_decoder_inst *di_to)
643 {
644
645         if (session_is_valid(sess) != SRD_OK) {
646                 srd_err("Invalid session.");
647                 return SRD_ERR_ARG;
648         }
649
650         if (!di_from || !di_to) {
651                 srd_err("Invalid from/to instance pair.");
652                 return SRD_ERR_ARG;
653         }
654
655         if (g_slist_find(sess->di_list, di_to)) {
656                 /* Remove from the unstacked list. */
657                 sess->di_list = g_slist_remove(sess->di_list, di_to);
658         }
659
660         /* Stack on top of source di. */
661         di_from->next_di = g_slist_append(di_from->next_di, di_to);
662
663         return SRD_OK;
664 }
665
666 /**
667  * Find a decoder instance by its instance ID.
668  *
669  * Only the bottom level of instances are searched -- instances already stacked
670  * on top of another one will not be found.
671  *
672  * @param sess The session holding the protocol decoder instance.
673  * @param inst_id The instance ID to be found.
674  *
675  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
676  *
677  * @since 0.3.0
678  */
679 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
680                 const char *inst_id)
681 {
682         GSList *l;
683         struct srd_decoder_inst *tmp, *di;
684
685         if (session_is_valid(sess) != SRD_OK) {
686                 srd_err("Invalid session.");
687                 return NULL;
688         }
689
690         di = NULL;
691         for (l = sess->di_list; l; l = l->next) {
692                 tmp = l->data;
693                 if (!strcmp(tmp->inst_id, inst_id)) {
694                         di = tmp;
695                         break;
696                 }
697         }
698
699         return di;
700 }
701
702 static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
703                 struct srd_session *sess, const GSList *stack,
704                 const PyObject *obj)
705 {
706         const GSList *l;
707         struct srd_decoder_inst *tmp, *di;
708
709         if (session_is_valid(sess) != SRD_OK) {
710                 srd_err("Invalid session.");
711                 return NULL;
712         }
713
714         di = NULL;
715         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
716                 tmp = l->data;
717                 if (tmp->py_inst == obj)
718                         di = tmp;
719                 else if (tmp->next_di)
720                         di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
721         }
722
723         return di;
724 }
725
726 /**
727  * Find a decoder instance by its Python object.
728  *
729  * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
730  * This will recurse to find the instance anywhere in the stack tree of all
731  * sessions.
732  *
733  * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
734  *              stack to search. To start searching at the bottom level of
735  *              decoder instances, pass NULL.
736  * @param obj The Python class instantiation.
737  *
738  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
739  *
740  * @private
741  *
742  * @since 0.1.0
743  */
744 SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
745                 const PyObject *obj)
746 {
747         struct srd_decoder_inst *di;
748         struct srd_session *sess;
749         GSList *l;
750
751         di = NULL;
752         for (l = sessions; di == NULL && l != NULL; l = l->next) {
753                 sess = l->data;
754                 di = srd_sess_inst_find_by_obj(sess, stack, obj);
755         }
756
757         return di;
758 }
759
760 /** @private */
761 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
762 {
763         PyObject *py_res;
764         GSList *l;
765         struct srd_decoder_inst *next_di;
766         int ret;
767
768         srd_dbg("Calling start() method on protocol decoder instance %s.",
769                         di->inst_id);
770
771         if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
772                 srd_exception_catch("Protocol decoder instance %s: ",
773                                 di->inst_id);
774                 return SRD_ERR_PYTHON;
775         }
776         Py_DecRef(py_res);
777
778         /* Start all the PDs stacked on top of this one. */
779         for (l = di->next_di; l; l = l->next) {
780                 next_di = l->data;
781                 if ((ret = srd_inst_start(next_di)) != SRD_OK)
782                         return ret;
783         }
784
785         return SRD_OK;
786 }
787
788 /**
789  * Run the specified decoder function.
790  *
791  * @param di The decoder instance to call. Must not be NULL.
792  * @param start_samplenum The starting sample number for the buffer's sample
793  *                        set, relative to the start of capture.
794  * @param end_samplenum The ending sample number for the buffer's sample
795  *                        set, relative to the start of capture.
796  * @param inbuf The buffer to decode. Must not be NULL.
797  * @param inbuflen Length of the buffer. Must be > 0.
798  *
799  * @return SRD_OK upon success, a (negative) error code otherwise.
800  *
801  * @private
802  *
803  * @since 0.1.0
804  */
805 SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
806                 uint64_t start_samplenum, uint64_t end_samplenum,
807                 const uint8_t *inbuf, uint64_t inbuflen)
808 {
809         PyObject *py_res;
810         srd_logic *logic;
811
812         srd_dbg("Calling decode() on instance %s with %" PRIu64 " bytes "
813                 "starting at sample %" PRIu64 ".", di->inst_id, inbuflen,
814                 start_samplenum);
815
816         /* Return an error upon unusable input. */
817         if (!di) {
818                 srd_dbg("empty decoder instance");
819                 return SRD_ERR_ARG;
820         }
821         if (!inbuf) {
822                 srd_dbg("NULL buffer pointer");
823                 return SRD_ERR_ARG;
824         }
825         if (inbuflen == 0) {
826                 srd_dbg("empty buffer");
827                 return SRD_ERR_ARG;
828         }
829
830         /*
831          * Create new srd_logic object. Each iteration around the PD's loop
832          * will fill one sample into this object.
833          */
834         logic = PyObject_New(srd_logic, &srd_logic_type);
835         Py_INCREF(logic);
836         logic->di = (struct srd_decoder_inst *)di;
837         logic->start_samplenum = start_samplenum;
838         logic->itercnt = 0;
839         logic->inbuf = (uint8_t *)inbuf;
840         logic->inbuflen = inbuflen;
841         logic->sample = PyList_New(2);
842         Py_INCREF(logic->sample);
843
844         Py_IncRef(di->py_inst);
845         if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
846                         "KKO", start_samplenum, end_samplenum, logic))) {
847                 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
848                 return SRD_ERR_PYTHON;
849         }
850         Py_DecRef(py_res);
851
852         return SRD_OK;
853 }
854
855 /** @private */
856 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
857 {
858         GSList *l;
859         struct srd_pd_output *pdo;
860
861         srd_dbg("Freeing instance %s", di->inst_id);
862
863         Py_DecRef(di->py_inst);
864         g_free(di->inst_id);
865         g_free(di->dec_probemap);
866         g_slist_free(di->next_di);
867         for (l = di->pd_output; l; l = l->next) {
868                 pdo = l->data;
869                 g_free(pdo->proto_id);
870                 g_free(pdo);
871         }
872         g_slist_free(di->pd_output);
873         g_free(di);
874 }
875
876 /** @private */
877 SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack)
878 {
879         GSList *l;
880         struct srd_decoder_inst *di;
881
882         if (session_is_valid(sess) != SRD_OK) {
883                 srd_err("Invalid session.");
884                 return;
885         }
886
887         di = NULL;
888         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
889                 di = l->data;
890                 if (di->next_di)
891                         srd_inst_free_all(sess, di->next_di);
892                 srd_inst_free(di);
893         }
894         if (!stack) {
895                 g_slist_free(sess->di_list);
896                 sess->di_list = NULL;
897         }
898 }
899
900 /** @} */
901