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
21 #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 sigrokdecode_load_decoder(const char *name,
51 struct sigrokdecode_decoder **dec);
54 * Initialize libsigrokdecode.
56 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
58 int sigrokdecode_init(void)
63 struct sigrokdecode_decoder *dec;
66 /* Py_Initialize() returns void and usually cannot fail. */
69 /* Add search directory for the protocol decoders. */
70 /* FIXME: Check error code. */
71 /* FIXME: What happens if this function is called multiple times? */
72 PyRun_SimpleString("import sys;"
73 "sys.path.append(r'" DECODERS_DIR "');");
75 if (!(dir = opendir(DECODERS_DIR)))
76 return SIGROKDECODE_ERR_DECODERS_DIR;
78 while ((dp = readdir(dir)) != NULL) {
79 if (!g_str_has_suffix(dp->d_name, ".py"))
82 /* Decoder name == filename (without .py suffix). */
83 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
85 /* TODO: Error handling. */
86 dec = malloc(sizeof(struct sigrokdecode_decoder));
88 /* Load the decoder. */
89 ret = sigrokdecode_load_decoder(decodername, &dec);
91 /* Append it to the list of supported/loaded decoders. */
92 list_pds = g_slist_append(list_pds, dec);
96 return SIGROKDECODE_OK;
100 * Returns the list of supported/loaded protocol decoders.
102 * This is a GSList containing the names of the decoders as strings.
104 * @return List of decoders, NULL if none are supported or loaded.
106 GSList *sigrokdecode_list_decoders(void)
112 * Get the decoder with the specified ID.
114 * @param id The ID string of the decoder to return.
115 * @return The decoder with the specified ID, or NULL if not found.
117 struct sigrokdecode_decoder *sigrokdecode_get_decoder_by_id(const char *id)
120 struct sigrokdecode_decoder *dec;
122 for (l = sigrokdecode_list_decoders(); l; l = l->next) {
124 if (!strcmp(dec->id, id))
132 * Helper function to handle Python strings.
134 * TODO: @param entries.
136 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
137 * The 'outstr' argument points to a malloc()ed string upon success.
139 static int h_str(PyObject *py_res, PyObject *py_func, PyObject *py_mod,
140 const char *key, char **outstr)
146 py_str = PyMapping_GetItemString(py_res, (char *)key);
147 if (!py_str || !PyString_Check(py_str)) {
148 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
149 goto err_h_decref_func;
153 * PyString_AsString()'s returned string refers to an internal buffer
154 * (not a copy), i.e. the data must not be modified, and the memory
155 * must not be free()'d.
157 if (!(str = PyString_AsString(py_str))) {
158 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
159 goto err_h_decref_str;
162 if (!(*outstr = strdup(str))) {
163 ret = SIGROKDECODE_ERR_MALLOC;
164 goto err_h_decref_str;
169 return SIGROKDECODE_OK;
177 if (PyErr_Occurred())
178 PyErr_Print(); /* Returns void. */
188 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
190 static int sigrokdecode_load_decoder(const char *name,
191 struct sigrokdecode_decoder **dec)
193 struct sigrokdecode_decoder *d;
194 PyObject *py_mod, *py_func, *py_res /* , *py_tuple */;
197 /* "Import" the Python module. */
198 if (!(py_mod = PyImport_ImportModule(name))) { /* NEWREF */
199 PyErr_Print(); /* Returns void. */
200 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
203 /* Get the 'register' function name as Python callable object. */
204 py_func = PyObject_GetAttrString(py_mod, "register"); /* NEWREF */
205 if (!py_func || !PyCallable_Check(py_func)) {
206 if (PyErr_Occurred())
207 PyErr_Print(); /* Returns void. */
209 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
212 /* Call the 'register' function without arguments, get the result. */
213 if (!(py_res = PyObject_CallFunction(py_func, NULL))) { /* NEWREF */
214 PyErr_Print(); /* Returns void. */
217 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
220 if (!(d = malloc(sizeof(struct sigrokdecode_decoder))))
221 return SIGROKDECODE_ERR_MALLOC;
223 if ((r = h_str(py_res, py_func, py_mod, "id", &(d->id))) < 0)
226 if ((r = h_str(py_res, py_func, py_mod, "name", &(d->name))) < 0)
229 if ((r = h_str(py_res, py_func, py_mod, "desc", &(d->desc))) < 0)
237 /* Get the 'decode' function name as Python callable object. */
238 py_func = PyObject_GetAttrString(py_mod, "decode"); /* NEWREF */
239 if (!py_func || !PyCallable_Check(py_func)) {
240 if (PyErr_Occurred())
241 PyErr_Print(); /* Returns void. */
243 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
246 d->py_func = py_func;
248 /* TODO: Handle inputformats, outputformats. */
252 return SIGROKDECODE_OK;
256 * Run the specified decoder function.
260 * @param inbuflen TODO
262 * @param outbuflen TODO
264 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
266 int sigrokdecode_run_decoder(struct sigrokdecode_decoder *dec,
267 uint8_t *inbuf, uint64_t inbuflen,
268 uint8_t **outbuf, uint64_t *outbuflen)
270 PyObject *py_mod, *py_func, *py_args, *py_value, *py_res;
273 /* TODO: Use #defines for the return codes. */
275 /* Return an error upon unusable input. */
277 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
279 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
280 if (inbuflen == 0) /* No point in working on empty buffers. */
281 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
283 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
284 if (outbuflen == NULL)
285 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
287 /* TODO: Error handling. */
288 py_mod = dec->py_mod;
290 py_func = dec->py_func;
293 /* Create a Python tuple of size 1. */
294 if (!(py_args = PyTuple_New(1))) { /* NEWREF */
295 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
296 goto err_run_decref_func;
299 /* Get the input buffer as Python "string" (byte array). */
300 /* TODO: int vs. uint64_t for 'inbuflen'? */
301 if (!(py_value = Py_BuildValue("s#", inbuf, inbuflen))) { /* NEWREF */
302 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
303 goto err_run_decref_args;
307 * IMPORTANT: PyTuple_SetItem() "steals" a reference to py_value!
308 * That means we are no longer responsible for Py_XDECREF()'ing it.
309 * It will automatically be free'd when the 'py_args' tuple is free'd.
311 if (PyTuple_SetItem(py_args, 0, py_value) != 0) { /* STEAL */
312 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
313 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
314 goto err_run_decref_args;
317 if (!(py_res = PyObject_CallObject(py_func, py_args))) { /* NEWREF */
318 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
319 goto err_run_decref_args;
322 if ((r = PyObject_AsCharBuffer(py_res, (const char **)outbuf,
323 (Py_ssize_t *)outbuflen))) {
324 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
326 goto err_run_decref_args;
329 ret = SIGROKDECODE_OK;
339 if (PyErr_Occurred())
340 PyErr_Print(); /* Returns void. */
346 * Shutdown libsigrokdecode.
348 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
350 int sigrokdecode_shutdown(void)
352 /* Py_Finalize() returns void, any finalization errors are ignored. */
355 return SIGROKDECODE_OK;