2 * This file is part of the sigrok project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
21 #include "sigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "sigrokdecode-internal.h"
29 static GSList *di_list = NULL;
30 static GSList *callbacks = NULL;
32 /* lives in decoder.c */
33 extern GSList *pd_list;
35 /* lives in module_sigrokdecode.c */
36 extern PyMODINIT_FUNC PyInit_sigrokdecode(void);
38 /* lives in type_logic.c */
39 extern PyTypeObject srd_logic_type;
43 * Initialize libsigrokdecode.
45 * This initializes the Python interpreter, and creates and initializes
46 * a "sigrok" Python module with a single put() method.
48 * Then, it searches for sigrok protocol decoder files (*.py) in the
49 * "decoders" subdirectory of the the sigrok installation directory.
50 * All decoders that are found are loaded into memory and added to an
51 * internal list of decoders, which can be queried via srd_list_decoders().
53 * The caller is responsible for calling the clean-up function srd_exit(),
54 * which will properly shut down libsigrokdecode and free its allocated memory.
56 * Multiple calls to srd_init(), without calling srd_exit() in between,
59 * @return SRD_OK upon success, a (negative) error code otherwise.
60 * Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
61 * directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
62 * If not enough memory could be allocated, return SRD_ERR_MALLOC.
68 PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
70 /* Py_Initialize() returns void and usually cannot fail. */
73 if ((ret = set_modulepath()) != SRD_OK) {
78 if ((ret = srd_load_all_decoders()) != SRD_OK) {
88 * Shutdown libsigrokdecode.
90 * This frees all the memory allocated for protocol decoders and shuts down
91 * the Python interpreter.
93 * This function should only be called if there was a (successful!) invocation
94 * of srd_init() before. Calling this function multiple times in a row, without
95 * any successful srd_init() calls in between, is not allowed.
97 * @return SRD_OK upon success, a (negative) error code otherwise.
101 /* Unload/free all decoders, and then the list of decoders itself. */
102 /* TODO: Error handling. */
103 srd_unload_all_decoders();
104 g_slist_free(pd_list);
106 /* Py_Finalize() returns void, any finalization errors are ignored. */
114 * Add search directories for the protocol decoders.
116 * TODO: add path from env var SIGROKDECODE_PATH, config etc
117 * TODO: Should take directoryname/path as input.
119 int set_modulepath(void)
128 * On Windows/MinGW, Python's sys.path needs entries of the form
129 * 'C:\\foo\\bar' instead of '/foo/bar'.
132 splitted = g_strsplit(DECODERS_DIR, "/", 0);
133 path = g_build_pathv("\\\\", splitted);
134 g_strfreev(splitted);
136 path = g_strdup(DECODERS_DIR);
139 /* TODO: Prepend instead of appending. */
140 /* TODO: Sanity check on 'path' (length, escape special chars, ...). */
141 s = g_strdup_printf("import sys; sys.path.append(r'%s')", path);
143 ret = PyRun_SimpleString(s);
153 * Set options in a decoder instance.
155 * @param di Decoder instance.
156 * @param options A GHashTable of options to set.
158 * Handled options are removed from the hash.
160 * @return SRD_OK upon success, a (negative) error code otherwise.
162 int srd_instance_set_options(struct srd_decoder_instance *di,
165 PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
166 PyObject *py_optlist, *py_classval;
168 unsigned long long int val_ull;
169 int num_optkeys, ret, size, i;
172 if(!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
173 /* Decoder has no options. */
174 if (g_hash_table_size(options) == 0) {
175 /* No options provided. */
178 srd_err("Protocol decoder has no options.");
184 ret = SRD_ERR_PYTHON;
186 py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
187 py_optlist = py_classval = NULL;
188 py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");
189 if (!PyDict_Check(py_dec_options)) {
190 srd_err("Protocol decoder %s options is not a dictionary.",
195 /* All of these are synthesized objects, so they're good. */
196 py_dec_optkeys = PyDict_Keys(py_dec_options);
197 num_optkeys = PyList_Size(py_dec_optkeys);
198 if (!(py_di_options = PyObject_GetAttrString(di->py_instance, "options")))
200 for (i = 0; i < num_optkeys; i++) {
201 /* Get the default class value for this option. */
202 py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
203 if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
205 if (!(py_classval = PyList_GetItem(py_optlist, 1)))
207 if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) {
208 srd_err("Options of type %s are not yet supported.", Py_TYPE(py_classval)->tp_name);
212 if ((value = g_hash_table_lookup(options, key))) {
213 /* An override for this option was provided. */
214 if (PyUnicode_Check(py_classval)) {
215 if (!(py_optval = PyUnicode_FromString(value))) {
216 /* Some UTF-8 encoding error. */
220 } else if (PyLong_Check(py_classval)) {
221 if (!(py_optval = PyLong_FromString(value, NULL, 0))) {
222 /* ValueError Exception */
224 srd_err("Option %s has invalid value %s: expected integer",
229 g_hash_table_remove(options, key);
231 /* Use the class default for this option. */
232 if (PyUnicode_Check(py_classval)) {
233 /* Make a brand new copy of the string. */
234 py_ustr = PyUnicode_AS_UNICODE(py_classval);
235 size = PyUnicode_GET_SIZE(py_classval);
236 py_optval = PyUnicode_FromUnicode(py_ustr, size);
237 } else if (PyLong_Check(py_classval)) {
238 /* Make a brand new copy of the integer. */
239 val_ull = PyLong_AsUnsignedLongLong(py_classval);
240 if (val_ull == (unsigned long long)-1) {
241 /* OverFlowError exception */
243 srd_err("Invalid integer value for %s: expected integer", key);
246 if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
251 /* If we got here, py_optval holds a known good new reference
252 * to the instance option to set.
254 if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
261 Py_XDECREF(py_optlist);
262 Py_XDECREF(py_di_options);
263 Py_XDECREF(py_dec_optkeys);
264 Py_XDECREF(py_dec_options);
267 if (PyErr_Occurred()) {
268 srd_dbg("stray exception!");
277 * Set probes in a decoder instance.
279 * @param di Decoder instance.
280 * @param probes A GHashTable of probes to set. Key is probe name, value is
281 * the probe number. Samples passed to this instance will be arranged in this
284 * Handled probes are removed from the hash.
286 * @return SRD_OK upon success, a (negative) error code otherwise.
288 int srd_instance_set_probes(struct srd_decoder_instance *di,
293 if (g_hash_table_size(probes) == 0)
294 /* No probes provided. */
297 if(!PyObject_HasAttrString(di->decoder->py_dec, "probes"))
298 /* Decoder has no probes. */
301 ret = SRD_ERR_PYTHON;
304 if (g_hash_table_size(probes) > 0) {
305 srd_err("Setting probes is not yet supported.");
306 return SRD_ERR_PYTHON;
315 * Create a new protocol decoder instance.
317 * @param id Decoder 'id' field.
318 * @param options GHashtable of options which override the defaults set in
320 * @return Pointer to a newly allocated struct srd_decoder_instance, or
321 * NULL in case of failure.
323 struct srd_decoder_instance *srd_instance_new(const char *decoder_id,
326 struct srd_decoder *dec;
327 struct srd_decoder_instance *di;
330 srd_dbg("%s: creating new %s instance", __func__, decoder_id);
332 if (!(dec = srd_get_decoder_by_id(decoder_id))) {
333 srd_err("Protocol decoder %s not found.", decoder_id);
337 if (!(di = g_try_malloc0(sizeof(*di)))) {
338 srd_err("Failed to malloc instance.");
342 instance_id = g_hash_table_lookup(options, "id");
344 di->instance_id = g_strdup(instance_id ? instance_id : decoder_id);
345 g_hash_table_remove(options, "id");
347 /* Create a new instance of this decoder class. */
348 if (!(di->py_instance = PyObject_CallObject(dec->py_dec, NULL))) {
349 if (PyErr_Occurred())
355 /* Instance takes input from a frontend by default. */
356 di_list = g_slist_append(di_list, di);
358 if (srd_instance_set_options(di, options) != SRD_OK) {
359 di_list = g_slist_remove(di_list, di);
367 int srd_instance_stack(struct srd_decoder_instance *di_from,
368 struct srd_decoder_instance *di_to)
371 if (!di_from || !di_to) {
372 srd_err("invalid from/to instance pair");
376 if (!g_slist_find(di_list, di_from)) {
377 srd_err("unstacked instance not found");
381 /* Remove from the unstacked list. */
382 di_list = g_slist_remove(di_list, di_to);
384 /* Stack on top of source di. */
385 di_from->next_di = g_slist_append(di_from->next_di, di_to);
391 /* TODO: this should go into the PD stack */
392 struct srd_decoder_instance *srd_instance_find(char *instance_id)
395 struct srd_decoder_instance *tmp, *di;
398 for (l = di_list; l; l = l->next) {
400 if (!strcmp(tmp->instance_id, instance_id)) {
409 int srd_instance_start(struct srd_decoder_instance *di, PyObject *args)
411 PyObject *py_name, *py_res;
413 srd_dbg("calling start() method on protocol decoder instance %s", di->instance_id);
415 if (!(py_name = PyUnicode_FromString("start"))) {
416 srd_err("unable to build python object for 'start'");
417 if (PyErr_Occurred())
419 return SRD_ERR_PYTHON;
422 if (!(py_res = PyObject_CallMethodObjArgs(di->py_instance,
423 py_name, args, NULL))) {
424 if (PyErr_Occurred())
426 return SRD_ERR_PYTHON;
436 * Run the specified decoder function.
440 * @param inbuflen TODO
442 * @return SRD_OK upon success, a (negative) error code otherwise.
444 int srd_instance_decode(uint64_t start_samplenum,
445 struct srd_decoder_instance *di, uint8_t *inbuf, uint64_t inbuflen)
447 PyObject *py_instance, *py_res;
449 uint64_t end_samplenum;
451 /* Return an error upon unusable input. */
453 return SRD_ERR_ARG; /* TODO: More specific error? */
455 return SRD_ERR_ARG; /* TODO: More specific error? */
456 if (inbuflen == 0) /* No point in working on empty buffers. */
457 return SRD_ERR_ARG; /* TODO: More specific error? */
459 /* TODO: Error handling. */
460 py_instance = di->py_instance;
461 Py_XINCREF(py_instance);
463 logic = PyObject_New(srd_logic, &srd_logic_type);
466 logic->start_samplenum = start_samplenum;
468 logic->inbuf = inbuf;
469 logic->inbuflen = inbuflen;
470 logic->sample = PyList_New(2);
471 Py_INCREF(logic->sample);
473 end_samplenum = start_samplenum + inbuflen / di->unitsize;
474 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
475 "KKO", logic->start_samplenum, end_samplenum, logic))) {
476 if (PyErr_Occurred())
477 PyErr_Print(); /* Returns void. */
479 return SRD_ERR_PYTHON; /* TODO: More specific error? */
488 int srd_session_start(int num_probes, int unitsize, uint64_t samplerate)
492 struct srd_decoder_instance *di;
495 if (!(args = Py_BuildValue("{s:l}", "samplerate", (long)samplerate))) {
496 srd_err("unable to build python object for metadata");
497 return SRD_ERR_PYTHON;
500 /* Run the start() method on all decoders receiving frontend data. */
501 for (d = di_list; d; d = d->next) {
503 di->num_probes = num_probes;
504 di->unitsize = unitsize;
505 di->samplerate = samplerate;
506 if ((ret = srd_instance_start(di, args) != SRD_OK))
509 /* Run the start() method on all decoders up the stack from this one. */
510 for (s = di->next_di; s; s = s->next) {
511 /* These don't need probes, unitsize and samplerate. */
513 if ((ret = srd_instance_start(di, args) != SRD_OK))
523 /* Feed logic samples to decoder session. */
524 int srd_session_feed(uint64_t start_samplenum, uint8_t *inbuf, uint64_t inbuflen)
529 for (d = di_list; d; d = d->next) {
530 if ((ret = srd_instance_decode(start_samplenum, d->data, inbuf,
531 inbuflen)) != SRD_OK)
539 int pd_add(struct srd_decoder_instance *di, int output_type,
542 struct srd_pd_output *pdo;
544 if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output))))
547 /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
548 pdo->pdo_id = g_slist_length(di->pd_output);
549 pdo->output_type = output_type;
550 pdo->decoder = di->decoder;
551 pdo->proto_id = g_strdup(proto_id);
552 di->pd_output = g_slist_append(di->pd_output, pdo);
557 struct srd_decoder_instance *get_di_by_decobject(void *decobject)
560 struct srd_decoder_instance *di;
562 for (l = di_list; l; l = l->next) {
564 if (decobject == di->py_instance)
566 /* Check decoders stacked on top of this one. */
567 for (s = di->next_di; s; s = s->next) {
569 if (decobject == di->py_instance)
577 int srd_register_callback(int output_type, void *cb)
579 struct srd_pd_callback *pd_cb;
581 if (!(pd_cb = g_try_malloc(sizeof(struct srd_pd_callback))))
582 return SRD_ERR_MALLOC;
584 pd_cb->output_type = output_type;
585 pd_cb->callback = cb;
586 callbacks = g_slist_append(callbacks, pd_cb);
591 void *srd_find_callback(int output_type)
594 struct srd_pd_callback *pd_cb;
598 for (l = callbacks; l; l = l->next) {
600 if (pd_cb->output_type == output_type) {
601 cb = pd_cb->callback;