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