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 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);
53 * Initialize libsigrokdecode.
55 * @return SRD_OK upon success, a (negative) error code otherwise.
62 struct srd_decoder *dec;
65 /* Py_Initialize() returns void and usually cannot fail. */
68 /* Add search directory for the protocol decoders. */
69 /* FIXME: Check error code. */
70 /* FIXME: What happens if this function is called multiple times? */
71 PyRun_SimpleString("import sys;"
72 "sys.path.append(r'" DECODERS_DIR "');");
74 if (!(dir = opendir(DECODERS_DIR)))
75 return SRD_ERR_DECODERS_DIR;
77 while ((dp = readdir(dir)) != NULL) {
78 if (!g_str_has_suffix(dp->d_name, ".py"))
81 /* Decoder name == filename (without .py suffix). */
82 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
84 /* TODO: Error handling. */
85 dec = malloc(sizeof(struct srd_decoder));
87 /* Load the decoder. */
88 ret = srd_load_decoder(decodername, &dec);
90 /* Append it to the list of supported/loaded decoders. */
91 list_pds = g_slist_append(list_pds, dec);
99 * Returns the list of supported/loaded protocol decoders.
101 * This is a GSList containing the names of the decoders as strings.
103 * @return List of decoders, NULL if none are supported or loaded.
105 GSList *srd_list_decoders(void)
111 * Get the decoder with the specified ID.
113 * @param id The ID string of the decoder to return.
114 * @return The decoder with the specified ID, or NULL if not found.
116 struct srd_decoder *srd_get_decoder_by_id(const char *id)
119 struct srd_decoder *dec;
121 for (l = srd_list_decoders(); l; l = l->next) {
123 if (!strcmp(dec->id, id))
131 * Helper function to handle Python strings.
133 * TODO: @param entries.
135 * @return SRD_OK upon success, a (negative) error code otherwise.
136 * The 'outstr' argument points to a malloc()ed string upon success.
138 static int h_str(PyObject *py_res, PyObject *py_func, PyObject *py_mod,
139 const char *key, char **outstr)
145 py_str = PyMapping_GetItemString(py_res, (char *)key);
146 if (!py_str || !PyString_Check(py_str)) {
147 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
148 goto err_h_decref_func;
152 * PyString_AsString()'s returned string refers to an internal buffer
153 * (not a copy), i.e. the data must not be modified, and the memory
154 * must not be free()'d.
156 if (!(str = PyString_AsString(py_str))) {
157 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
158 goto err_h_decref_str;
161 if (!(*outstr = g_strdup(str))) {
162 ret = SRD_ERR_MALLOC;
163 goto err_h_decref_str;
176 if (PyErr_Occurred())
177 PyErr_Print(); /* Returns void. */
187 * @return SRD_OK upon success, a (negative) error code otherwise.
189 static int srd_load_decoder(const char *name,
190 struct srd_decoder **dec)
192 struct srd_decoder *d;
193 PyObject *py_mod, *py_func, *py_res /* , *py_tuple */;
196 /* "Import" the Python module. */
197 if (!(py_mod = PyImport_ImportModule(name))) { /* NEWREF */
198 PyErr_Print(); /* Returns void. */
199 return SRD_ERR_PYTHON; /* TODO: More specific error? */
202 /* Get the 'register' function name as Python callable object. */
203 py_func = PyObject_GetAttrString(py_mod, "register"); /* NEWREF */
204 if (!py_func || !PyCallable_Check(py_func)) {
205 if (PyErr_Occurred())
206 PyErr_Print(); /* Returns void. */
208 return SRD_ERR_PYTHON; /* TODO: More specific error? */
211 /* Call the 'register' function without arguments, get the result. */
212 if (!(py_res = PyObject_CallFunction(py_func, NULL))) { /* NEWREF */
213 PyErr_Print(); /* Returns void. */
216 return SRD_ERR_PYTHON; /* TODO: More specific error? */
219 if (!(d = malloc(sizeof(struct srd_decoder))))
220 return SRD_ERR_MALLOC;
222 if ((r = h_str(py_res, py_func, py_mod, "id", &(d->id))) < 0)
225 if ((r = h_str(py_res, py_func, py_mod, "name", &(d->name))) < 0)
228 if ((r = h_str(py_res, py_func, py_mod, "desc", &(d->desc))) < 0)
236 /* Get the 'decode' function name as Python callable object. */
237 py_func = PyObject_GetAttrString(py_mod, "decode"); /* NEWREF */
238 if (!py_func || !PyCallable_Check(py_func)) {
239 if (PyErr_Occurred())
240 PyErr_Print(); /* Returns void. */
242 return SRD_ERR_PYTHON; /* TODO: More specific error? */
245 d->py_func = py_func;
247 /* TODO: Handle func, inputformats, outputformats. */
248 /* Note: They must at least be set to NULL, will segfault otherwise. */
250 d->inputformats = NULL;
251 d->outputformats = NULL;
259 * Run the specified decoder function.
263 * @param inbuflen TODO
265 * @param outbuflen TODO
267 * @return SRD_OK upon success, a (negative) error code otherwise.
269 int srd_run_decoder(struct srd_decoder *dec,
270 uint8_t *inbuf, uint64_t inbuflen,
271 uint8_t **outbuf, uint64_t *outbuflen)
273 PyObject *py_mod, *py_func, *py_args, *py_value, *py_res;
276 /* TODO: Use #defines for the return codes. */
278 /* Return an error upon unusable input. */
280 return SRD_ERR_ARGS; /* TODO: More specific error? */
282 return SRD_ERR_ARGS; /* TODO: More specific error? */
283 if (inbuflen == 0) /* No point in working on empty buffers. */
284 return SRD_ERR_ARGS; /* TODO: More specific error? */
286 return SRD_ERR_ARGS; /* TODO: More specific error? */
287 if (outbuflen == NULL)
288 return SRD_ERR_ARGS; /* TODO: More specific error? */
290 /* TODO: Error handling. */
291 py_mod = dec->py_mod;
293 py_func = dec->py_func;
296 /* Create a Python tuple of size 1. */
297 if (!(py_args = PyTuple_New(1))) { /* NEWREF */
298 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
299 goto err_run_decref_func;
302 /* Get the input buffer as Python "string" (byte array). */
303 /* TODO: int vs. uint64_t for 'inbuflen'? */
304 if (!(py_value = Py_BuildValue("s#", inbuf, inbuflen))) { /* NEWREF */
305 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
306 goto err_run_decref_args;
310 * IMPORTANT: PyTuple_SetItem() "steals" a reference to py_value!
311 * That means we are no longer responsible for Py_XDECREF()'ing it.
312 * It will automatically be free'd when the 'py_args' tuple is free'd.
314 if (PyTuple_SetItem(py_args, 0, py_value) != 0) { /* STEAL */
315 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
316 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
317 goto err_run_decref_args;
320 if (!(py_res = PyObject_CallObject(py_func, py_args))) { /* NEWREF */
321 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
322 goto err_run_decref_args;
325 if ((r = PyObject_AsCharBuffer(py_res, (const char **)outbuf,
326 (Py_ssize_t *)outbuflen))) {
327 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
329 goto err_run_decref_args;
342 if (PyErr_Occurred())
343 PyErr_Print(); /* Returns void. */
351 static int srd_unload_decoder(struct srd_decoder *dec)
358 /* TODO: Free everything in inputformats and outputformats. */
360 if (dec->inputformats != NULL)
361 g_slist_free(dec->inputformats);
362 if (dec->outputformats != NULL)
363 g_slist_free(dec->outputformats);
365 Py_XDECREF(dec->py_func);
366 Py_XDECREF(dec->py_mod);
374 static int srd_unload_all_decoders(void)
377 struct srd_decoder *dec;
379 for (l = srd_list_decoders(); l; l = l->next) {
381 /* TODO: Error handling. */
382 srd_unload_decoder(dec);
389 * Shutdown libsigrokdecode.
391 * @return SRD_OK upon success, a (negative) error code otherwise.
395 /* Unload/free all decoders, and then the list of decoders itself. */
396 /* TODO: Error handling. */
397 srd_unload_all_decoders();
398 g_slist_free(list_pds);
400 /* Py_Finalize() returns void, any finalization errors are ignored. */