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");
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(0))) { /* 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.
311 /* Create an instance of the Decoder class */
312 py_instance = PyObject_Call(py_res, py_args, py_value);
314 if (PyErr_Occurred())
315 PyErr_Print(); /* Returns void. */
316 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
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? */
324 d->py_instance = py_instance;
326 /* TODO: Handle func, inputformats, outputformats. */
327 /* Note: They must at least be set to NULL, will segfault otherwise. */
329 d->inputformats = NULL;
330 d->outputformats = NULL;
338 * Run the specified decoder function.
342 * @param inbuflen TODO
344 * @param outbuflen TODO
346 * @return SRD_OK upon success, a (negative) error code otherwise.
348 int srd_run_decoder(struct srd_decoder *dec,
349 uint8_t *inbuf, uint64_t inbuflen,
350 uint8_t **outbuf, uint64_t *outbuflen)
352 PyObject *py_mod, *py_instance, *py_args, *py_value, *py_res;
355 /* FIXME: Don't have a timebase available here. Make one up. */
356 static int _timehack = 0;
357 _timehack += inbuflen;
359 /* TODO: Use #defines for the return codes. */
361 /* Return an error upon unusable input. */
363 return SRD_ERR_ARGS; /* TODO: More specific error? */
365 return SRD_ERR_ARGS; /* TODO: More specific error? */
366 if (inbuflen == 0) /* No point in working on empty buffers. */
367 return SRD_ERR_ARGS; /* TODO: More specific error? */
369 return SRD_ERR_ARGS; /* TODO: More specific error? */
370 if (outbuflen == NULL)
371 return SRD_ERR_ARGS; /* TODO: More specific error? */
373 /* TODO: Error handling. */
374 py_mod = dec->py_mod;
376 py_instance = dec->py_instance;
377 Py_XINCREF(py_instance);
379 /* Create a Python tuple of size 1. */
380 if (!(py_args = PyTuple_New(1))) { /* NEWREF */
381 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
382 goto err_run_decref_func;
385 /* Get the input buffer as Python "string" (byte array). */
386 /* TODO: int vs. uint64_t for 'inbuflen'? */
388 py_value = Py_BuildValue("{sisiss#}",
391 "data", inbuf, inbuflen / _unitsize
394 if (!(py_res = PyObject_CallMethod(py_instance, "decode",
395 "O", py_value))) { /* NEWREF */
396 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
397 goto err_run_decref_args;
408 Py_XDECREF(py_instance);
411 if (PyErr_Occurred())
412 PyErr_Print(); /* Returns void. */
420 static int srd_unload_decoder(struct srd_decoder *dec)
427 /* TODO: Free everything in inputformats and outputformats. */
429 if (dec->inputformats != NULL)
430 g_slist_free(dec->inputformats);
431 if (dec->outputformats != NULL)
432 g_slist_free(dec->outputformats);
434 Py_XDECREF(dec->py_instance);
435 Py_XDECREF(dec->py_mod);
443 static int srd_unload_all_decoders(void)
446 struct srd_decoder *dec;
448 for (l = srd_list_decoders(); l; l = l->next) {
450 /* TODO: Error handling. */
451 srd_unload_decoder(dec);
458 * Shutdown libsigrokdecode.
460 * @return SRD_OK upon success, a (negative) error code otherwise.
464 /* Unload/free all decoders, and then the list of decoders itself. */
465 /* TODO: Error handling. */
466 srd_unload_all_decoders();
467 g_slist_free(list_pds);
469 /* Py_Finalize() returns void, any finalization errors are ignored. */