]> sigrok.org Git - libsigrokdecode.git/blame - decode.c
Simplified code for calling Python decode method.
[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
052f32ee 62 fprintf(stderr, "sigrok.put() called by decoder:\n");
3b24e378
KS
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. */
052f32ee 296 if (!(py_args = PyTuple_New(0))) { /* NEWREF */
3b24e378
KS
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 );
3b24e378 311 /* Create an instance of the Decoder class */
052f32ee 312 py_instance = PyObject_Call(py_res, py_args, py_value);
3b24e378
KS
313 if (!py_instance) {
314 if (PyErr_Occurred())
315 PyErr_Print(); /* Returns void. */
316 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
317 Py_XDECREF(py_res);
318 Py_XDECREF(py_mod);
319 fprintf(stderr, "Unable to create instance of Decoder class in PD module %s\n", name);
320 return SRD_ERR_PYTHON; /* TODO: More specific error? */
052f32ee 321 }
5c55017c
UH
322 }
323
052f32ee 324 d->py_instance = py_instance;
5c55017c 325
f9b54a6c
UH
326 /* TODO: Handle func, inputformats, outputformats. */
327 /* Note: They must at least be set to NULL, will segfault otherwise. */
328 d->func = NULL;
329 d->inputformats = NULL;
330 d->outputformats = NULL;
5c55017c
UH
331
332 *dec = d;
910e5fd8 333
d752b12b 334 return SRD_OK;
1c6fa20f
UH
335}
336
337/**
338 * Run the specified decoder function.
339 *
5c55017c 340 * @param dec TODO
1c6fa20f
UH
341 * @param inbuf TODO
342 * @param inbuflen TODO
343 * @param outbuf TODO
344 * @param outbuflen TODO
70e44845 345 *
d752b12b 346 * @return SRD_OK upon success, a (negative) error code otherwise.
1c6fa20f 347 */
d752b12b 348int srd_run_decoder(struct srd_decoder *dec,
2b45dd71 349 uint8_t *inbuf, uint64_t inbuflen,
350 uint8_t **outbuf, uint64_t *outbuflen)
1c6fa20f 351{
052f32ee 352 PyObject *py_mod, *py_instance, *py_args, *py_value, *py_res;
036e6f67 353 int r, ret;
9d29ffad
KS
354
355 /* FIXME: Don't have a timebase available here. Make one up. */
356 static int _timehack = 0;
357 _timehack += inbuflen;
1c6fa20f
UH
358
359 /* TODO: Use #defines for the return codes. */
360
361 /* Return an error upon unusable input. */
5c55017c 362 if (dec == NULL)
d752b12b 363 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 364 if (inbuf == NULL)
d752b12b 365 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 366 if (inbuflen == 0) /* No point in working on empty buffers. */
d752b12b 367 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 368 if (outbuf == NULL)
d752b12b 369 return SRD_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 370 if (outbuflen == NULL)
d752b12b 371 return SRD_ERR_ARGS; /* TODO: More specific error? */
922763ab 372
5c55017c
UH
373 /* TODO: Error handling. */
374 py_mod = dec->py_mod;
2557ad9d 375 Py_XINCREF(py_mod);
052f32ee
GM
376 py_instance = dec->py_instance;
377 Py_XINCREF(py_instance);
1c6fa20f
UH
378
379 /* Create a Python tuple of size 1. */
6b08da24 380 if (!(py_args = PyTuple_New(1))) { /* NEWREF */
d752b12b 381 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
036e6f67 382 goto err_run_decref_func;
1c6fa20f
UH
383 }
384
9d29ffad
KS
385 /* Get the input buffer as Python "string" (byte array). */
386 /* TODO: int vs. uint64_t for 'inbuflen'? */
387
388 py_value = Py_BuildValue("{sisiss#}",
389 "time", _timehack,
390 "duration", 10,
391 "data", inbuf, inbuflen / _unitsize
392 );
393
052f32ee
GM
394 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
395 "O", py_value))) { /* NEWREF */
9d29ffad
KS
396 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
397 goto err_run_decref_args;
398 }
399
1c6fa20f 400
d752b12b 401 ret = SRD_OK;
036e6f67 402
2557ad9d 403 Py_XDECREF(py_res);
036e6f67
UH
404
405err_run_decref_args:
2557ad9d 406 Py_XDECREF(py_args);
036e6f67 407err_run_decref_func:
052f32ee 408 Py_XDECREF(py_instance);
2557ad9d 409 Py_XDECREF(py_mod);
1c6fa20f 410
036e6f67
UH
411 if (PyErr_Occurred())
412 PyErr_Print(); /* Returns void. */
413
414 return ret;
1c6fa20f
UH
415}
416
f9b54a6c
UH
417/**
418 * TODO
419 */
d752b12b 420static int srd_unload_decoder(struct srd_decoder *dec)
f9b54a6c
UH
421{
422 g_free(dec->id);
423 g_free(dec->name);
424 g_free(dec->desc);
425 g_free(dec->func);
426
427 /* TODO: Free everything in inputformats and outputformats. */
428
429 if (dec->inputformats != NULL)
430 g_slist_free(dec->inputformats);
431 if (dec->outputformats != NULL)
432 g_slist_free(dec->outputformats);
433
052f32ee 434 Py_XDECREF(dec->py_instance);
f9b54a6c
UH
435 Py_XDECREF(dec->py_mod);
436
d752b12b 437 return SRD_OK;
f9b54a6c
UH
438}
439
440/**
441 * TODO
442 */
d752b12b 443static int srd_unload_all_decoders(void)
f9b54a6c
UH
444{
445 GSList *l;
d752b12b 446 struct srd_decoder *dec;
f9b54a6c 447
d752b12b 448 for (l = srd_list_decoders(); l; l = l->next) {
f9b54a6c
UH
449 dec = l->data;
450 /* TODO: Error handling. */
d752b12b 451 srd_unload_decoder(dec);
f9b54a6c
UH
452 }
453
d752b12b 454 return SRD_OK;
f9b54a6c
UH
455}
456
1c6fa20f
UH
457/**
458 * Shutdown libsigrokdecode.
459 *
d752b12b 460 * @return SRD_OK upon success, a (negative) error code otherwise.
1c6fa20f 461 */
7ea73e33 462int srd_exit(void)
1c6fa20f 463{
f9b54a6c
UH
464 /* Unload/free all decoders, and then the list of decoders itself. */
465 /* TODO: Error handling. */
d752b12b 466 srd_unload_all_decoders();
f9b54a6c
UH
467 g_slist_free(list_pds);
468
1c6fa20f
UH
469 /* Py_Finalize() returns void, any finalization errors are ignored. */
470 Py_Finalize();
471
d752b12b 472 return SRD_OK;
1c6fa20f 473}