]> sigrok.org Git - libsigrokdecode.git/blame_incremental - decode.c
decode.c: Simplify the import code.
[libsigrokdecode.git] / decode.c
... / ...
CommitLineData
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
21#include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
22#include <stdio.h>
23#include <string.h>
24#include <dirent.h>
25#include <config.h>
26
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
34/* The list of protocol decoders. */
35GSList *list_pds = NULL;
36
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 *
42 * - If it returns a "new reference", you're responsible to Py_XDECREF() it.
43 *
44 * - If it returns a "borrowed reference", you MUST NOT Py_XDECREF() it.
45 *
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).
48 */
49
50/**
51 * Initialize libsigrokdecode.
52 *
53 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
54 */
55int sigrokdecode_init(void)
56{
57 DIR *dir;
58 struct dirent *dp;
59 char *tmp;
60
61 /* Py_Initialize() returns void and usually cannot fail. */
62 Py_Initialize();
63
64 /* Add search directory for the protocol decoders. */
65 /* FIXME: Check error code. */
66 /* FIXME: What happens if this function is called multiple times? */
67 PyRun_SimpleString("import sys;"
68 "sys.path.append(r'" DECODERS_DIR "');");
69
70 if (!(dir = opendir(DECODERS_DIR)))
71 return SIGROKDECODE_ERR_DECODERS_DIR;
72
73 while ((dp = readdir(dir)) != NULL) {
74 if (!g_str_has_suffix(dp->d_name, ".py"))
75 continue;
76 /* For now use the filename (without .py) as decoder name. */
77 if ((tmp = g_strndup(dp->d_name, strlen(dp->d_name) - 3)))
78 list_pds = g_slist_append(list_pds, tmp);
79 }
80 closedir(dir);
81
82 return SIGROKDECODE_OK;
83}
84
85/**
86 * Returns the list of supported/loaded protocol decoders.
87 *
88 * This is a GSList containing the names of the decoders as strings.
89 *
90 * @return List of decoders, NULL if none are supported or loaded.
91 */
92GSList *sigrokdecode_list_decoders(void)
93{
94 return list_pds;
95}
96
97/**
98 * Helper function to handle Python strings.
99 *
100 * TODO: @param entries.
101 *
102 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
103 * The 'outstr' argument points to a malloc()ed string upon success.
104 */
105static int h_str(PyObject *py_res, PyObject *py_func, PyObject *py_mod,
106 const char *key, char **outstr)
107{
108 PyObject *py_str;
109 char *str;
110 int ret;
111
112 py_str = PyMapping_GetItemString(py_res, (char *)key);
113 if (!py_str || !PyString_Check(py_str)) {
114 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
115 goto err_h_decref_func;
116 }
117
118 /*
119 * PyString_AsString()'s returned string refers to an internal buffer
120 * (not a copy), i.e. the data must not be modified, and the memory
121 * must not be free()'d.
122 */
123 if (!(str = PyString_AsString(py_str))) {
124 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
125 goto err_h_decref_str;
126 }
127
128 if (!(*outstr = strdup(str))) {
129 ret = SIGROKDECODE_ERR_MALLOC;
130 goto err_h_decref_str;
131 }
132
133 Py_XDECREF(py_str);
134
135 return SIGROKDECODE_OK;
136
137err_h_decref_str:
138 Py_XDECREF(py_str);
139err_h_decref_func:
140 Py_XDECREF(py_func);
141err_h_decref_mod:
142 Py_XDECREF(py_mod);
143
144 if (PyErr_Occurred())
145 PyErr_Print(); /* Returns void. */
146
147 return ret;
148}
149
150/**
151 * TODO
152 *
153 * @param name TODO
154 *
155 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
156 */
157int sigrokdecode_load_decoder(const char *name,
158 struct sigrokdecode_decoder **dec)
159{
160 struct sigrokdecode_decoder *d;
161 PyObject *py_mod, *py_func, *py_res /* , *py_tuple */;
162 int r;
163
164 /* "Import" the Python module. */
165 if (!(py_mod = PyImport_ImportModule(name))) { /* NEWREF */
166 PyErr_Print(); /* Returns void. */
167 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
168 }
169
170 /* Get the 'register' function name as Python callable object. */
171 py_func = PyObject_GetAttrString(py_mod, "register"); /* NEWREF */
172 if (!py_func || !PyCallable_Check(py_func)) {
173 if (PyErr_Occurred())
174 PyErr_Print(); /* Returns void. */
175 Py_XDECREF(py_mod);
176 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
177 }
178
179 /* Call the 'register' function without arguments, get the result. */
180 if (!(py_res = PyObject_CallFunction(py_func, NULL))) { /* NEWREF */
181 PyErr_Print(); /* Returns void. */
182 Py_XDECREF(py_func);
183 Py_XDECREF(py_mod);
184 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
185 }
186
187 if (!(d = malloc(sizeof(struct sigrokdecode_decoder))))
188 return SIGROKDECODE_ERR_MALLOC;
189
190 if ((r = h_str(py_res, py_func, py_mod, "id", &(d->id))) < 0)
191 return r;
192
193 if ((r = h_str(py_res, py_func, py_mod, "name", &(d->name))) < 0)
194 return r;
195
196 if ((r = h_str(py_res, py_func, py_mod, "desc", &(d->desc))) < 0)
197 return r;
198
199 d->py_mod = py_mod;
200
201 Py_XDECREF(py_res);
202 Py_XDECREF(py_func);
203
204 /* Get the 'decode' function name as Python callable object. */
205 py_func = PyObject_GetAttrString(py_mod, "decode"); /* NEWREF */
206 if (!py_func || !PyCallable_Check(py_func)) {
207 if (PyErr_Occurred())
208 PyErr_Print(); /* Returns void. */
209 Py_XDECREF(py_mod);
210 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
211 }
212
213 d->py_func = py_func;
214
215 /* TODO: Handle inputformats, outputformats. */
216
217 *dec = d;
218
219 return SIGROKDECODE_OK;
220}
221
222/**
223 * Run the specified decoder function.
224 *
225 * @param dec TODO
226 * @param inbuf TODO
227 * @param inbuflen TODO
228 * @param outbuf TODO
229 * @param outbuflen TODO
230 *
231 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
232 */
233int sigrokdecode_run_decoder(struct sigrokdecode_decoder *dec,
234 uint8_t *inbuf, uint64_t inbuflen,
235 uint8_t **outbuf, uint64_t *outbuflen)
236{
237 PyObject *py_mod, *py_func, *py_args, *py_value, *py_res;
238 int r, ret;
239
240 /* TODO: Use #defines for the return codes. */
241
242 /* Return an error upon unusable input. */
243 if (dec == NULL)
244 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
245 if (inbuf == NULL)
246 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
247 if (inbuflen == 0) /* No point in working on empty buffers. */
248 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
249 if (outbuf == NULL)
250 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
251 if (outbuflen == NULL)
252 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
253
254 /* TODO: Error handling. */
255 py_mod = dec->py_mod;
256 Py_XINCREF(py_mod);
257 py_func = dec->py_func;
258 Py_XINCREF(py_func);
259
260 /* Create a Python tuple of size 1. */
261 if (!(py_args = PyTuple_New(1))) { /* NEWREF */
262 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
263 goto err_run_decref_func;
264 }
265
266 /* Get the input buffer as Python "string" (byte array). */
267 /* TODO: int vs. uint64_t for 'inbuflen'? */
268 if (!(py_value = Py_BuildValue("s#", inbuf, inbuflen))) { /* NEWREF */
269 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
270 goto err_run_decref_args;
271 }
272
273 /*
274 * IMPORTANT: PyTuple_SetItem() "steals" a reference to py_value!
275 * That means we are no longer responsible for Py_XDECREF()'ing it.
276 * It will automatically be free'd when the 'py_args' tuple is free'd.
277 */
278 if (PyTuple_SetItem(py_args, 0, py_value) != 0) { /* STEAL */
279 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
280 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
281 goto err_run_decref_args;
282 }
283
284 if (!(py_res = PyObject_CallObject(py_func, py_args))) { /* NEWREF */
285 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
286 goto err_run_decref_args;
287 }
288
289 if ((r = PyObject_AsCharBuffer(py_res, (const char **)outbuf,
290 (Py_ssize_t *)outbuflen))) {
291 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
292 Py_XDECREF(py_res);
293 goto err_run_decref_args;
294 }
295
296 ret = SIGROKDECODE_OK;
297
298 Py_XDECREF(py_res);
299
300err_run_decref_args:
301 Py_XDECREF(py_args);
302err_run_decref_func:
303 Py_XDECREF(py_func);
304err_run_decref_mod:
305 Py_XDECREF(py_mod);
306
307 if (PyErr_Occurred())
308 PyErr_Print(); /* Returns void. */
309
310 return ret;
311}
312
313/**
314 * Shutdown libsigrokdecode.
315 *
316 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
317 */
318int sigrokdecode_shutdown(void)
319{
320 /* Py_Finalize() returns void, any finalization errors are ignored. */
321 Py_Finalize();
322
323 return SIGROKDECODE_OK;
324}