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