2 * This file is part of the sigrok project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
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.
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.
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
22 #include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
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
34 /* The list of protocol decoders. */
35 static GSList *list_pds = NULL;
38 * Here's a quick overview of Python/C API reference counting.
40 * Check the Python/C API docs for what type of reference a function returns.
42 * - If it returns a "new reference", you're responsible to Py_XDECREF() it.
44 * - If it returns a "borrowed reference", you MUST NOT Py_XDECREF() it.
46 * - If a function "steals" a reference, you no longer are responsible for
47 * Py_XDECREF()ing it (someone else will do it for you at some point).
50 static int srd_load_decoder(const char *name, struct srd_decoder **dec);
52 static int _unitsize = 1;
55 emb_put(PyObject *self, PyObject *args)
59 if (!PyArg_ParseTuple(args, "O:put", &arg))
62 fprintf(stderr, "sigrok.put() called by decoder:\n", arg);
63 PyObject_Print(arg, stdout, Py_PRINT_RAW);
68 static PyMethodDef EmbMethods[] = {
69 {"put", emb_put, METH_VARARGS,
70 "Accepts a dictionary with the following keys: time, duration, data"},
75 * Initialize libsigrokdecode.
77 * @return SRD_OK upon success, a (negative) error code otherwise.
84 struct srd_decoder *dec;
87 /* Py_Initialize() returns void and usually cannot fail. */
90 Py_InitModule("sigrok", EmbMethods);
92 /* Add search directory for the protocol decoders. */
93 /* FIXME: Check error code. */
94 /* FIXME: What happens if this function is called multiple times? */
95 PyRun_SimpleString("import sys;"
96 "sys.path.append(r'" DECODERS_DIR "');");
98 if (!(dir = opendir(DECODERS_DIR)))
99 return SRD_ERR_DECODERS_DIR;
101 while ((dp = readdir(dir)) != NULL) {
102 if (!g_str_has_suffix(dp->d_name, ".py"))
105 /* Decoder name == filename (without .py suffix). */
106 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
108 /* TODO: Error handling. */
109 dec = malloc(sizeof(struct srd_decoder));
111 /* Load the decoder. */
112 ret = srd_load_decoder(decodername, &dec);
115 /* Append it to the list of supported/loaded decoders. */
116 list_pds = g_slist_append(list_pds, dec);
125 * Returns the list of supported/loaded protocol decoders.
127 * This is a GSList containing the names of the decoders as strings.
129 * @return List of decoders, NULL if none are supported or loaded.
131 GSList *srd_list_decoders(void)
137 * Get the decoder with the specified ID.
139 * @param id The ID string of the decoder to return.
140 * @return The decoder with the specified ID, or NULL if not found.
142 struct srd_decoder *srd_get_decoder_by_id(const char *id)
145 struct srd_decoder *dec;
147 for (l = srd_list_decoders(); l; l = l->next) {
149 if (!strcmp(dec->id, id))
157 * Helper function to handle Python strings.
159 * TODO: @param entries.
161 * @return SRD_OK upon success, a (negative) error code otherwise.
162 * The 'outstr' argument points to a malloc()ed string upon success.
164 static int h_str(PyObject *py_res, PyObject *py_mod,
165 const char *key, char **outstr)
171 py_str = PyMapping_GetItemString(py_res, (char *)key);
172 if (!py_str || !PyString_Check(py_str)) {
173 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
174 goto err_h_decref_mod;
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.
182 if (!(str = PyString_AsString(py_str))) {
183 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
184 goto err_h_decref_str;
187 if (!(*outstr = g_strdup(str))) {
188 ret = SRD_ERR_MALLOC;
189 goto err_h_decref_str;
201 if (PyErr_Occurred())
202 PyErr_Print(); /* Returns void. */
212 * @return SRD_OK upon success, a (negative) error code otherwise.
214 static int srd_load_decoder(const char *name,
215 struct srd_decoder **dec)
217 struct srd_decoder *d;
218 PyObject *py_mod, *py_func, *py_res, *py_instance = NULL, *py_args, *py_value/* , *py_tuple */;
220 fprintf(stdout, "\n%s\n", name);
222 /* "Import" the Python module. */
223 if (!(py_mod = PyImport_ImportModule(name))) { /* NEWREF */
224 PyErr_Print(); /* Returns void. */
225 return SRD_ERR_PYTHON; /* TODO: More specific error? */
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)) {
231 if (PyErr_Occurred())
232 PyErr_Print(); /* Returns void. */
234 fprintf(stderr, "register dictionary was not found or is declared a function.\n");
235 return SRD_ERR_PYTHON; /* TODO: More specific error? */
239 if (!(d = malloc(sizeof(struct srd_decoder))))
240 return SRD_ERR_MALLOC;
242 if ((r = h_str(py_res, py_mod, "id", &(d->id))) < 0)
245 if ((r = h_str(py_res, py_mod, "name", &(d->name))) < 0)
248 if ((r = h_str(py_res, py_mod, "longname",
249 &(d->longname))) < 0)
252 if ((r = h_str(py_res, py_mod, "desc", &(d->desc))) < 0)
255 if ((r = h_str(py_res, py_mod, "longdesc",
256 &(d->longdesc))) < 0)
259 if ((r = h_str(py_res, py_mod, "author", &(d->author))) < 0)
262 if ((r = h_str(py_res, py_mod, "email", &(d->email))) < 0)
265 if ((r = h_str(py_res, py_mod, "license", &(d->license))) < 0)
273 /* Get the 'Decoder' class as Python object. */
274 py_res = PyObject_GetAttrString(py_mod, "Decoder"); /* NEWREF */
276 if (PyErr_Occurred())
277 PyErr_Print(); /* Returns void. */
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? */
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. */
289 return SRD_ERR_PYTHON; /* TODO: More specific error? */
292 PyObject_Print(py_res, stdout, Py_PRINT_RAW);
293 fprintf(stdout, "\n");
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. */
303 return SRD_ERR_PYTHON; /* TODO: More specific error? */
306 py_value = Py_BuildValue("{sssisd}",
308 "unitsize", _unitsize, //FIXME: Pass in a unitsize that matches the selected LA
309 "starttime", 129318231823.0 //TODO: Fill with something reasonable.
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.
316 if (PyTuple_SetItem(py_args, 0, py_value) != 0) { /* STEAL */
317 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
320 return SRD_ERR_PYTHON; /* TODO: More specific error? */
323 /* Create an instance of the Decoder class */
324 py_instance = PyObject_CallObject(py_res, py_args);
326 if (PyErr_Occurred())
327 PyErr_Print(); /* Returns void. */
328 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
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? */
334 /* OK, we have successfully created an instance of the Decoder object */
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);
344 return SRD_ERR_PYTHON; /* TODO: More specific error? */
349 d->py_decodefunc = py_func;
351 /* TODO: Handle func, inputformats, outputformats. */
352 /* Note: They must at least be set to NULL, will segfault otherwise. */
354 d->inputformats = NULL;
355 d->outputformats = NULL;
363 * Run the specified decoder function.
367 * @param inbuflen TODO
369 * @param outbuflen TODO
371 * @return SRD_OK upon success, a (negative) error code otherwise.
373 int srd_run_decoder(struct srd_decoder *dec,
374 uint8_t *inbuf, uint64_t inbuflen,
375 uint8_t **outbuf, uint64_t *outbuflen)
377 PyObject *py_mod, *py_func, *py_args, *py_value, *py_res;
380 /* FIXME: Don't have a timebase available here. Make one up. */
381 static int _timehack = 0;
382 _timehack += inbuflen;
384 /* TODO: Use #defines for the return codes. */
386 /* Return an error upon unusable input. */
388 return SRD_ERR_ARGS; /* TODO: More specific error? */
390 return SRD_ERR_ARGS; /* TODO: More specific error? */
391 if (inbuflen == 0) /* No point in working on empty buffers. */
392 return SRD_ERR_ARGS; /* TODO: More specific error? */
394 return SRD_ERR_ARGS; /* TODO: More specific error? */
395 if (outbuflen == NULL)
396 return SRD_ERR_ARGS; /* TODO: More specific error? */
398 /* TODO: Error handling. */
399 py_mod = dec->py_mod;
401 py_func = dec->py_decodefunc;
404 /* Create a Python tuple of size 1. */
405 if (!(py_args = PyTuple_New(1))) { /* NEWREF */
406 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
407 goto err_run_decref_func;
410 /* Get the input buffer as Python "string" (byte array). */
411 /* TODO: int vs. uint64_t for 'inbuflen'? */
413 py_value = Py_BuildValue("{sisiss#}",
416 "data", inbuf, inbuflen / _unitsize
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.
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;
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;
446 if (PyErr_Occurred())
447 PyErr_Print(); /* Returns void. */
455 static int srd_unload_decoder(struct srd_decoder *dec)
462 /* TODO: Free everything in inputformats and outputformats. */
464 if (dec->inputformats != NULL)
465 g_slist_free(dec->inputformats);
466 if (dec->outputformats != NULL)
467 g_slist_free(dec->outputformats);
469 Py_XDECREF(dec->py_decodefunc);
470 Py_XDECREF(dec->py_mod);
478 static int srd_unload_all_decoders(void)
481 struct srd_decoder *dec;
483 for (l = srd_list_decoders(); l; l = l->next) {
485 /* TODO: Error handling. */
486 srd_unload_decoder(dec);
493 * Shutdown libsigrokdecode.
495 * @return SRD_OK upon success, a (negative) error code otherwise.
499 /* Unload/free all decoders, and then the list of decoders itself. */
500 /* TODO: Error handling. */
501 srd_unload_all_decoders();
502 g_slist_free(list_pds);
504 /* Py_Finalize() returns void, any finalization errors are ignored. */