]> sigrok.org Git - libsigrokdecode.git/blame - decode.c
nunchuk.py: Fix indentation (syntax error).
[libsigrokdecode.git] / decode.c
CommitLineData
1c6fa20f
UH
1/*
2 * This file is part of the sigrok project.
3 *
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
17830fe1 21#include "config.h"
1c6fa20f
UH
22#include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
23#include <stdio.h>
5c55017c 24#include <string.h>
7c24d086 25#include <dirent.h>
1c6fa20f 26
e6c7a826
UH
27/* Re-define some string functions for Python >= 3.0. */
28#if PY_VERSION_HEX >= 0x03000000
29#define PyString_AsString PyBytes_AsString
30#define PyString_FromString PyBytes_FromString
31#define PyString_Check PyBytes_Check
32#endif
33
7c24d086 34/* The list of protocol decoders. */
a0d48257 35static GSList *list_pds = NULL;
7c24d086 36
f800adc4
UH
37/*
38 * Here's a quick overview of Python/C API reference counting.
39 *
40 * Check the Python/C API docs for what type of reference a function returns.
41 *
2557ad9d 42 * - If it returns a "new reference", you're responsible to Py_XDECREF() it.
f800adc4 43 *
2557ad9d 44 * - If it returns a "borrowed reference", you MUST NOT Py_XDECREF() it.
f800adc4
UH
45 *
46 * - If a function "steals" a reference, you no longer are responsible for
2557ad9d 47 * Py_XDECREF()ing it (someone else will do it for you at some point).
f800adc4
UH
48 */
49
d752b12b 50static int srd_load_decoder(const char *name, struct srd_decoder **dec);
53bec0cf 51
922763ab
KS
52static int _unitsize = 1;
53
261d6532 54static PyObject *emb_put(PyObject *self, PyObject *args)
922763ab
KS
55{
56 PyObject *arg;
261d6532 57
6eb87578
GM
58 (void)self;
59
922763ab
KS
60 if (!PyArg_ParseTuple(args, "O:put", &arg))
61 return NULL;
62
74911b4c 63 fprintf(stdout, "sigrok.put() called by decoder:\n");
3b24e378 64 PyObject_Print(arg, stdout, Py_PRINT_RAW);
74911b4c 65 puts("");
3b24e378 66
922763ab
KS
67 Py_RETURN_NONE;
68}
69
70static PyMethodDef EmbMethods[] = {
922763ab 71 {"put", emb_put, METH_VARARGS,
261d6532 72 "Accepts a dictionary with the following keys: time, duration, data"},
922763ab
KS
73 {NULL, NULL, 0, NULL}
74};
75
1c6fa20f
UH
76/**
77 * Initialize libsigrokdecode.
78 *
c75080f0
UH
79 * This initializes the Python interpreter, and creates and initializes
80 * a "sigrok" Python module with a single put() method.
81 *
82 * Then, it searches for sigrok protocol decoder files (*.py) in the
83 * "decoders" subdirectory of the the sigrok installation directory.
84 * All decoders that are found are loaded into memory and added to an
85 * internal list of decoders, which can be queried via srd_list_decoders().
86 *
87 * The caller is responsible for calling the clean-up function srd_exit(),
88 * which will properly shut down libsigrokdecode and free its allocated memory.
89 *
90 * Multiple calls to srd_init(), without calling srd_exit() inbetween,
91 * are not allowed.
92 *
d752b12b 93 * @return SRD_OK upon success, a (negative) error code otherwise.
c75080f0
UH
94 * Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
95 * directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
96 * If not enough memory could be allocated, return SRD_ERR_MALLOC.
1c6fa20f 97 */
d752b12b 98int srd_init(void)
1c6fa20f 99{
7c24d086
UH
100 DIR *dir;
101 struct dirent *dp;
53bec0cf 102 char *decodername;
d752b12b 103 struct srd_decoder *dec;
53bec0cf 104 int ret;
7c24d086 105
1c6fa20f
UH
106 /* Py_Initialize() returns void and usually cannot fail. */
107 Py_Initialize();
108
0d1cf0f8
UH
109 /* TODO: Use Py_InitModule3() to add a docstring? */
110 if (!Py_InitModule("sigrok", EmbMethods)) {
111 Py_Finalize(); /* Returns void. */
112 return SRD_ERR_PYTHON;
113 }
922763ab 114
0895f56a 115 /* Add search directory for the protocol decoders. */
70e44845 116 /* FIXME: What happens if this function is called multiple times? */
0d1cf0f8
UH
117 ret = PyRun_SimpleString("import sys;"
118 "sys.path.append(r'" DECODERS_DIR "');");
119 if (ret != 0) {
120 Py_Finalize(); /* Returns void. */
121 return SRD_ERR_PYTHON;
122 }
1c6fa20f 123
0d1cf0f8
UH
124 if (!(dir = opendir(DECODERS_DIR))) {
125 Py_Finalize(); /* Returns void. */
d752b12b 126 return SRD_ERR_DECODERS_DIR;
0d1cf0f8 127 }
7c24d086
UH
128
129 while ((dp = readdir(dir)) != NULL) {
261d6532 130 /* Ignore filenames which don't end with ".py". */
276b55eb 131 if (!g_str_has_suffix(dp->d_name, ".py"))
7c24d086 132 continue;
53bec0cf
UH
133
134 /* Decoder name == filename (without .py suffix). */
135 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
136
261d6532 137 /* TODO: Error handling. Use g_try_malloc(). */
0d1cf0f8
UH
138 if (!(dec = malloc(sizeof(struct srd_decoder)))) {
139 Py_Finalize(); /* Returns void. */
140 return SRD_ERR_MALLOC;
141 }
53bec0cf
UH
142
143 /* Load the decoder. */
0d1cf0f8 144 /* TODO: Warning if loading fails for a decoder. */
d752b12b 145 ret = srd_load_decoder(decodername, &dec);
261d6532 146 if (!ret) {
3b24e378
KS
147 /* Append it to the list of supported/loaded decoders. */
148 list_pds = g_slist_append(list_pds, dec);
149 }
7c24d086
UH
150 }
151 closedir(dir);
152
d752b12b 153 return SRD_OK;
1c6fa20f
UH
154}
155
871d21e2
UH
156/**
157 * Returns the list of supported/loaded protocol decoders.
158 *
159 * This is a GSList containing the names of the decoders as strings.
160 *
161 * @return List of decoders, NULL if none are supported or loaded.
162 */
d752b12b 163GSList *srd_list_decoders(void)
871d21e2
UH
164{
165 return list_pds;
166}
167
53bec0cf
UH
168/**
169 * Get the decoder with the specified ID.
170 *
171 * @param id The ID string of the decoder to return.
172 * @return The decoder with the specified ID, or NULL if not found.
173 */
d752b12b 174struct srd_decoder *srd_get_decoder_by_id(const char *id)
53bec0cf
UH
175{
176 GSList *l;
d752b12b 177 struct srd_decoder *dec;
53bec0cf 178
d752b12b 179 for (l = srd_list_decoders(); l; l = l->next) {
53bec0cf
UH
180 dec = l->data;
181 if (!strcmp(dec->id, id))
182 return dec;
183 }
184
185 return NULL;
186}
187
5c55017c
UH
188/**
189 * Helper function to handle Python strings.
190 *
191 * TODO: @param entries.
192 *
d752b12b 193 * @return SRD_OK upon success, a (negative) error code otherwise.
70e44845 194 * The 'outstr' argument points to a malloc()ed string upon success.
5c55017c 195 */
922763ab 196static int h_str(PyObject *py_res, PyObject *py_mod,
5c55017c
UH
197 const char *key, char **outstr)
198{
199 PyObject *py_str;
200 char *str;
f7313eea 201 int ret;
5c55017c 202
6eb87578 203 py_str = PyObject_GetAttrString(py_res, (char *)key); /* NEWREF */
5c55017c 204 if (!py_str || !PyString_Check(py_str)) {
d752b12b 205 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
922763ab 206 goto err_h_decref_mod;
5c55017c
UH
207 }
208
6b08da24
UH
209 /*
210 * PyString_AsString()'s returned string refers to an internal buffer
211 * (not a copy), i.e. the data must not be modified, and the memory
212 * must not be free()'d.
213 */
5c55017c 214 if (!(str = PyString_AsString(py_str))) {
d752b12b 215 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
f7313eea 216 goto err_h_decref_str;
5c55017c
UH
217 }
218
f9b54a6c 219 if (!(*outstr = g_strdup(str))) {
d752b12b 220 ret = SRD_ERR_MALLOC;
f7313eea 221 goto err_h_decref_str;
5c55017c
UH
222 }
223
2557ad9d 224 Py_XDECREF(py_str);
5c55017c 225
d752b12b 226 return SRD_OK;
f7313eea
UH
227
228err_h_decref_str:
229 Py_XDECREF(py_str);
922763ab 230err_h_decref_mod:
f7313eea
UH
231 Py_XDECREF(py_mod);
232
233 if (PyErr_Occurred())
234 PyErr_Print(); /* Returns void. */
235
236 return ret;
5c55017c
UH
237}
238
1c6fa20f
UH
239/**
240 * TODO
241 *
242 * @param name TODO
70e44845 243 *
d752b12b 244 * @return SRD_OK upon success, a (negative) error code otherwise.
1c6fa20f 245 */
261d6532 246static int srd_load_decoder(const char *name, struct srd_decoder **dec)
1c6fa20f 247{
d752b12b 248 struct srd_decoder *d;
6eb87578 249 PyObject *py_mod, *py_res;
5c55017c 250 int r;
261d6532 251
6eb87578 252 fprintf(stdout, "%s: %s\n", __func__, name);
5c55017c 253
5c55017c 254 /* "Import" the Python module. */
c7bb5dff 255 if (!(py_mod = PyImport_ImportModule(name))) { /* NEWREF */
6b08da24 256 PyErr_Print(); /* Returns void. */
d752b12b 257 return SRD_ERR_PYTHON; /* TODO: More specific error? */
5c55017c 258 }
5c55017c 259
6eb87578
GM
260 /* Get the 'Decoder' class as Python object. */
261 py_res = PyObject_GetAttrString(py_mod, "Decoder"); /* NEWREF */
262 if (!py_res) {
5c55017c 263 if (PyErr_Occurred())
6b08da24 264 PyErr_Print(); /* Returns void. */
2557ad9d 265 Py_XDECREF(py_mod);
6eb87578 266 fprintf(stderr, "Decoder class not found in PD module %s\n", name);
d752b12b 267 return SRD_ERR_PYTHON; /* TODO: More specific error? */
5c55017c
UH
268 }
269
d752b12b
UH
270 if (!(d = malloc(sizeof(struct srd_decoder))))
271 return SRD_ERR_MALLOC;
5c55017c 272
261d6532 273 /* We'll just use the name of the module for the ID. */
6eb87578 274 d->id = strdup(name);
5c55017c 275
922763ab 276 if ((r = h_str(py_res, py_mod, "name", &(d->name))) < 0)
5c55017c
UH
277 return r;
278
922763ab 279 if ((r = h_str(py_res, py_mod, "longname",
75a282e5
UH
280 &(d->longname))) < 0)
281 return r;
282
922763ab 283 if ((r = h_str(py_res, py_mod, "desc", &(d->desc))) < 0)
5c55017c
UH
284 return r;
285
922763ab 286 if ((r = h_str(py_res, py_mod, "longdesc",
75a282e5
UH
287 &(d->longdesc))) < 0)
288 return r;
289
922763ab 290 if ((r = h_str(py_res, py_mod, "author", &(d->author))) < 0)
75a282e5
UH
291 return r;
292
922763ab 293 if ((r = h_str(py_res, py_mod, "email", &(d->email))) < 0)
75a282e5
UH
294 return r;
295
922763ab 296 if ((r = h_str(py_res, py_mod, "license", &(d->license))) < 0)
75a282e5
UH
297 return r;
298
5c55017c 299 d->py_mod = py_mod;
6eb87578 300 d->py_decobj = py_res;
5c55017c 301
74911b4c
GM
302 /* TODO: Handle func, inputformats, outputformats. */
303 /* Note: They must at least be set to NULL, will segfault otherwise. */
304 d->func = NULL;
305 d->inputformats = NULL;
306 d->outputformats = NULL;
307
308 *dec = d;
309
310 return SRD_OK;
311}
312
313struct srd_decoder_instance *srd_instance_new(const char *id)
314{
261d6532
UH
315 struct srd_decoder *dec;
316 struct srd_decoder_instance *di;
74911b4c
GM
317 PyObject *py_args, *py_value;
318
261d6532
UH
319 if (!(dec = srd_get_decoder_by_id(id)))
320 return NULL;
321
322 /* TODO: Error handling. Use g_try_malloc(). */
323 di = g_malloc(sizeof(*di));
324
325 /* Create an empty Python tuple. */
6eb87578 326 if (!(py_args = PyTuple_New(0))) { /* NEWREF */
5c55017c 327 if (PyErr_Occurred())
6b08da24 328 PyErr_Print(); /* Returns void. */
261d6532 329
74911b4c 330 return NULL; /* TODO: More specific error? */
5c55017c 331 }
74911b4c 332
261d6532
UH
333 /*
334 * FIXME: Pass in a unitsize that matches the selected LA.
335 * FIXME: Fill 'starttime' with something reasonable.
336 */
337 py_value = Py_BuildValue("{sssisd}",
338 "driver", "demo",
339 "unitsize", _unitsize,
340 "starttime", 129318231823.0);
341
342 /* Create an instance of the 'Decoder' class. */
74911b4c
GM
343 di->py_instance = PyObject_Call(dec->py_decobj, py_args, py_value);
344 if (!di->py_instance) {
6eb87578
GM
345 if (PyErr_Occurred())
346 PyErr_Print(); /* Returns void. */
74911b4c 347 Py_XDECREF(py_args);
6eb87578 348 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
74911b4c 349 return NULL; /* TODO: More specific error? */
261d6532 350 }
5c55017c 351
74911b4c
GM
352 Py_XDECREF(py_args);
353 Py_XDECREF(py_value);
910e5fd8 354
74911b4c 355 return di;
1c6fa20f
UH
356}
357
f97f531c 358int srd_instance_set_probe(struct srd_decoder_instance *di,
261d6532 359 const char *probename, int num)
f97f531c
GM
360{
361 PyObject *probedict, *probenum;
261d6532 362
f97f531c
GM
363 probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
364 if (!probedict) {
365 if (PyErr_Occurred())
366 PyErr_Print(); /* Returns void. */
261d6532 367
f97f531c
GM
368 return SRD_ERR_PYTHON; /* TODO: More specific error? */
369 }
370
371 probenum = PyInt_FromLong(num);
261d6532 372 PyMapping_SetItemString(probedict, (char *)probename, probenum);
f97f531c
GM
373
374 Py_XDECREF(probenum);
375 Py_XDECREF(probedict);
261d6532 376
f97f531c
GM
377 return SRD_OK;
378}
379
1c6fa20f
UH
380/**
381 * Run the specified decoder function.
382 *
5c55017c 383 * @param dec TODO
1c6fa20f
UH
384 * @param inbuf TODO
385 * @param inbuflen TODO
386 * @param outbuf TODO
387 * @param outbuflen TODO
70e44845 388 *
d752b12b 389 * @return SRD_OK upon success, a (negative) error code otherwise.
1c6fa20f 390 */
74911b4c 391int srd_run_decoder(struct srd_decoder_instance *dec,
261d6532
UH
392 uint8_t *inbuf, uint64_t inbuflen,
393 uint8_t **outbuf, uint64_t *outbuflen)
1c6fa20f 394{
74911b4c 395 PyObject *py_instance, *py_value, *py_res;
f97f531c 396 int ret;
9d29ffad
KS
397 /* FIXME: Don't have a timebase available here. Make one up. */
398 static int _timehack = 0;
261d6532 399
9d29ffad 400 _timehack += inbuflen;
1c6fa20f
UH
401
402 /* TODO: Use #defines for the return codes. */
403
404 /* Return an error upon unusable input. */
5c55017c 405 if (dec == NULL)
d752b12b 406 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 407 if (inbuf == NULL)
d752b12b 408 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 409 if (inbuflen == 0) /* No point in working on empty buffers. */
d752b12b 410 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 411 if (outbuf == NULL)
d752b12b 412 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 413 if (outbuflen == NULL)
d752b12b 414 return SRD_ERR_ARGS; /* TODO: More specific error? */
261d6532 415
5c55017c 416 /* TODO: Error handling. */
052f32ee
GM
417 py_instance = dec->py_instance;
418 Py_XINCREF(py_instance);
1c6fa20f 419
9d29ffad
KS
420 /* Get the input buffer as Python "string" (byte array). */
421 /* TODO: int vs. uint64_t for 'inbuflen'? */
422
261d6532
UH
423 py_value = Py_BuildValue("{sisiss#}",
424 "time", _timehack,
425 "duration", 10,
426 "data", inbuf, inbuflen / _unitsize);
9d29ffad 427
261d6532
UH
428 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
429 "O", py_value))) { /* NEWREF */
9d29ffad
KS
430 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
431 goto err_run_decref_args;
432 }
433
d752b12b 434 ret = SRD_OK;
036e6f67 435
2557ad9d 436 Py_XDECREF(py_res);
036e6f67 437err_run_decref_args:
74911b4c 438 Py_XDECREF(py_value);
1c6fa20f 439
036e6f67
UH
440 if (PyErr_Occurred())
441 PyErr_Print(); /* Returns void. */
442
443 return ret;
1c6fa20f
UH
444}
445
f9b54a6c
UH
446/**
447 * TODO
448 */
d752b12b 449static int srd_unload_decoder(struct srd_decoder *dec)
f9b54a6c
UH
450{
451 g_free(dec->id);
452 g_free(dec->name);
453 g_free(dec->desc);
454 g_free(dec->func);
455
456 /* TODO: Free everything in inputformats and outputformats. */
457
458 if (dec->inputformats != NULL)
459 g_slist_free(dec->inputformats);
460 if (dec->outputformats != NULL)
461 g_slist_free(dec->outputformats);
462
74911b4c 463 Py_XDECREF(dec->py_decobj);
f9b54a6c
UH
464 Py_XDECREF(dec->py_mod);
465
0d1cf0f8
UH
466 /* TODO: (g_)free dec itself? */
467
d752b12b 468 return SRD_OK;
f9b54a6c
UH
469}
470
471/**
472 * TODO
473 */
d752b12b 474static int srd_unload_all_decoders(void)
f9b54a6c
UH
475{
476 GSList *l;
d752b12b 477 struct srd_decoder *dec;
f9b54a6c 478
d752b12b 479 for (l = srd_list_decoders(); l; l = l->next) {
f9b54a6c
UH
480 dec = l->data;
481 /* TODO: Error handling. */
d752b12b 482 srd_unload_decoder(dec);
f9b54a6c
UH
483 }
484
d752b12b 485 return SRD_OK;
f9b54a6c
UH
486}
487
1c6fa20f
UH
488/**
489 * Shutdown libsigrokdecode.
490 *
c75080f0
UH
491 * This frees all the memory allocated for protocol decoders and shuts down
492 * the Python interpreter.
493 *
494 * This function should only be called if there was a (successful!) invocation
495 * of srd_init() before. Calling this function multiple times in a row, without
496 * any successful srd_init() calls inbetween, is not allowed.
497 *
d752b12b 498 * @return SRD_OK upon success, a (negative) error code otherwise.
1c6fa20f 499 */
7ea73e33 500int srd_exit(void)
1c6fa20f 501{
f9b54a6c
UH
502 /* Unload/free all decoders, and then the list of decoders itself. */
503 /* TODO: Error handling. */
d752b12b 504 srd_unload_all_decoders();
f9b54a6c
UH
505 g_slist_free(list_pds);
506
1c6fa20f
UH
507 /* Py_Finalize() returns void, any finalization errors are ignored. */
508 Py_Finalize();
509
d752b12b 510 return SRD_OK;
1c6fa20f 511}