]> sigrok.org Git - libsigrokdecode.git/blame - decode.c
Properly free all memory upon sigrokdecode_shutdown().
[libsigrokdecode.git] / decode.c
CommitLineData
1c6fa20f
UH
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>
5c55017c 23#include <string.h>
7c24d086 24#include <dirent.h>
d842aebe 25#include <config.h>
1c6fa20f 26
e6c7a826
UH
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
7c24d086 34/* The list of protocol decoders. */
871d21e2 35GSList *list_pds = NULL;
7c24d086 36
f800adc4
UH
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 *
2557ad9d 42 * - If it returns a "new reference", you're responsible to Py_XDECREF() it.
f800adc4 43 *
2557ad9d 44 * - If it returns a "borrowed reference", you MUST NOT Py_XDECREF() it.
f800adc4
UH
45 *
46 * - If a function "steals" a reference, you no longer are responsible for
2557ad9d 47 * Py_XDECREF()ing it (someone else will do it for you at some point).
f800adc4
UH
48 */
49
53bec0cf
UH
50static int sigrokdecode_load_decoder(const char *name,
51 struct sigrokdecode_decoder **dec);
52
1c6fa20f
UH
53/**
54 * Initialize libsigrokdecode.
55 *
70e44845 56 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
1c6fa20f
UH
57 */
58int sigrokdecode_init(void)
59{
7c24d086
UH
60 DIR *dir;
61 struct dirent *dp;
53bec0cf
UH
62 char *decodername;
63 struct sigrokdecode_decoder *dec;
64 int ret;
7c24d086 65
1c6fa20f
UH
66 /* Py_Initialize() returns void and usually cannot fail. */
67 Py_Initialize();
68
0895f56a 69 /* Add search directory for the protocol decoders. */
2454527d 70 /* FIXME: Check error code. */
70e44845 71 /* FIXME: What happens if this function is called multiple times? */
0895f56a 72 PyRun_SimpleString("import sys;"
10426068 73 "sys.path.append(r'" DECODERS_DIR "');");
1c6fa20f 74
7c24d086
UH
75 if (!(dir = opendir(DECODERS_DIR)))
76 return SIGROKDECODE_ERR_DECODERS_DIR;
77
78 while ((dp = readdir(dir)) != NULL) {
276b55eb 79 if (!g_str_has_suffix(dp->d_name, ".py"))
7c24d086 80 continue;
53bec0cf
UH
81
82 /* Decoder name == filename (without .py suffix). */
83 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
84
85 /* TODO: Error handling. */
86 dec = malloc(sizeof(struct sigrokdecode_decoder));
87
88 /* Load the decoder. */
89 ret = sigrokdecode_load_decoder(decodername, &dec);
90
91 /* Append it to the list of supported/loaded decoders. */
92 list_pds = g_slist_append(list_pds, dec);
7c24d086
UH
93 }
94 closedir(dir);
95
70e44845 96 return SIGROKDECODE_OK;
1c6fa20f
UH
97}
98
871d21e2
UH
99/**
100 * Returns the list of supported/loaded protocol decoders.
101 *
102 * This is a GSList containing the names of the decoders as strings.
103 *
104 * @return List of decoders, NULL if none are supported or loaded.
105 */
106GSList *sigrokdecode_list_decoders(void)
107{
108 return list_pds;
109}
110
53bec0cf
UH
111/**
112 * Get the decoder with the specified ID.
113 *
114 * @param id The ID string of the decoder to return.
115 * @return The decoder with the specified ID, or NULL if not found.
116 */
117struct sigrokdecode_decoder *sigrokdecode_get_decoder_by_id(const char *id)
118{
119 GSList *l;
120 struct sigrokdecode_decoder *dec;
121
122 for (l = sigrokdecode_list_decoders(); l; l = l->next) {
123 dec = l->data;
124 if (!strcmp(dec->id, id))
125 return dec;
126 }
127
128 return NULL;
129}
130
5c55017c
UH
131/**
132 * Helper function to handle Python strings.
133 *
134 * TODO: @param entries.
135 *
3a9a7e38 136 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
70e44845 137 * The 'outstr' argument points to a malloc()ed string upon success.
5c55017c
UH
138 */
139static int h_str(PyObject *py_res, PyObject *py_func, PyObject *py_mod,
140 const char *key, char **outstr)
141{
142 PyObject *py_str;
143 char *str;
f7313eea 144 int ret;
5c55017c
UH
145
146 py_str = PyMapping_GetItemString(py_res, (char *)key);
147 if (!py_str || !PyString_Check(py_str)) {
f7313eea
UH
148 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
149 goto err_h_decref_func;
5c55017c
UH
150 }
151
6b08da24
UH
152 /*
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.
156 */
5c55017c 157 if (!(str = PyString_AsString(py_str))) {
f7313eea
UH
158 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
159 goto err_h_decref_str;
5c55017c
UH
160 }
161
f9b54a6c 162 if (!(*outstr = g_strdup(str))) {
f7313eea
UH
163 ret = SIGROKDECODE_ERR_MALLOC;
164 goto err_h_decref_str;
5c55017c
UH
165 }
166
2557ad9d 167 Py_XDECREF(py_str);
5c55017c 168
70e44845 169 return SIGROKDECODE_OK;
f7313eea
UH
170
171err_h_decref_str:
172 Py_XDECREF(py_str);
173err_h_decref_func:
174 Py_XDECREF(py_func);
f7313eea
UH
175 Py_XDECREF(py_mod);
176
177 if (PyErr_Occurred())
178 PyErr_Print(); /* Returns void. */
179
180 return ret;
5c55017c
UH
181}
182
1c6fa20f
UH
183/**
184 * TODO
185 *
186 * @param name TODO
70e44845 187 *
3a9a7e38 188 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
1c6fa20f 189 */
53bec0cf 190static int sigrokdecode_load_decoder(const char *name,
5c55017c 191 struct sigrokdecode_decoder **dec)
1c6fa20f 192{
5c55017c 193 struct sigrokdecode_decoder *d;
c7bb5dff 194 PyObject *py_mod, *py_func, *py_res /* , *py_tuple */;
5c55017c
UH
195 int r;
196
5c55017c 197 /* "Import" the Python module. */
c7bb5dff 198 if (!(py_mod = PyImport_ImportModule(name))) { /* NEWREF */
6b08da24 199 PyErr_Print(); /* Returns void. */
5c55017c
UH
200 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
201 }
5c55017c
UH
202
203 /* Get the 'register' function name as Python callable object. */
6b08da24 204 py_func = PyObject_GetAttrString(py_mod, "register"); /* NEWREF */
5c55017c
UH
205 if (!py_func || !PyCallable_Check(py_func)) {
206 if (PyErr_Occurred())
6b08da24 207 PyErr_Print(); /* Returns void. */
2557ad9d 208 Py_XDECREF(py_mod);
5c55017c
UH
209 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
210 }
211
212 /* Call the 'register' function without arguments, get the result. */
6b08da24
UH
213 if (!(py_res = PyObject_CallFunction(py_func, NULL))) { /* NEWREF */
214 PyErr_Print(); /* Returns void. */
2557ad9d
UH
215 Py_XDECREF(py_func);
216 Py_XDECREF(py_mod);
5c55017c
UH
217 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
218 }
219
220 if (!(d = malloc(sizeof(struct sigrokdecode_decoder))))
221 return SIGROKDECODE_ERR_MALLOC;
222
223 if ((r = h_str(py_res, py_func, py_mod, "id", &(d->id))) < 0)
224 return r;
225
226 if ((r = h_str(py_res, py_func, py_mod, "name", &(d->name))) < 0)
227 return r;
228
229 if ((r = h_str(py_res, py_func, py_mod, "desc", &(d->desc))) < 0)
230 return r;
231
232 d->py_mod = py_mod;
233
2557ad9d
UH
234 Py_XDECREF(py_res);
235 Py_XDECREF(py_func);
5c55017c
UH
236
237 /* Get the 'decode' function name as Python callable object. */
6b08da24 238 py_func = PyObject_GetAttrString(py_mod, "decode"); /* NEWREF */
5c55017c
UH
239 if (!py_func || !PyCallable_Check(py_func)) {
240 if (PyErr_Occurred())
6b08da24 241 PyErr_Print(); /* Returns void. */
2557ad9d 242 Py_XDECREF(py_mod);
5c55017c
UH
243 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
244 }
245
246 d->py_func = py_func;
247
f9b54a6c
UH
248 /* TODO: Handle func, inputformats, outputformats. */
249 /* Note: They must at least be set to NULL, will segfault otherwise. */
250 d->func = NULL;
251 d->inputformats = NULL;
252 d->outputformats = NULL;
5c55017c
UH
253
254 *dec = d;
910e5fd8 255
70e44845 256 return SIGROKDECODE_OK;
1c6fa20f
UH
257}
258
259/**
260 * Run the specified decoder function.
261 *
5c55017c 262 * @param dec TODO
1c6fa20f
UH
263 * @param inbuf TODO
264 * @param inbuflen TODO
265 * @param outbuf TODO
266 * @param outbuflen TODO
70e44845 267 *
3a9a7e38 268 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
1c6fa20f 269 */
5c55017c 270int sigrokdecode_run_decoder(struct sigrokdecode_decoder *dec,
2b45dd71 271 uint8_t *inbuf, uint64_t inbuflen,
272 uint8_t **outbuf, uint64_t *outbuflen)
1c6fa20f 273{
5c55017c 274 PyObject *py_mod, *py_func, *py_args, *py_value, *py_res;
036e6f67 275 int r, ret;
1c6fa20f
UH
276
277 /* TODO: Use #defines for the return codes. */
278
279 /* Return an error upon unusable input. */
5c55017c
UH
280 if (dec == NULL)
281 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 282 if (inbuf == NULL)
5c55017c 283 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 284 if (inbuflen == 0) /* No point in working on empty buffers. */
5c55017c 285 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 286 if (outbuf == NULL)
5c55017c 287 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 288 if (outbuflen == NULL)
5c55017c 289 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
1c6fa20f 290
5c55017c
UH
291 /* TODO: Error handling. */
292 py_mod = dec->py_mod;
2557ad9d 293 Py_XINCREF(py_mod);
5c55017c 294 py_func = dec->py_func;
2557ad9d 295 Py_XINCREF(py_func);
1c6fa20f
UH
296
297 /* Create a Python tuple of size 1. */
6b08da24 298 if (!(py_args = PyTuple_New(1))) { /* NEWREF */
036e6f67
UH
299 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
300 goto err_run_decref_func;
1c6fa20f
UH
301 }
302
303 /* Get the input buffer as Python "string" (byte array). */
304 /* TODO: int vs. uint64_t for 'inbuflen'? */
6b08da24 305 if (!(py_value = Py_BuildValue("s#", inbuf, inbuflen))) { /* NEWREF */
036e6f67
UH
306 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
307 goto err_run_decref_args;
1c6fa20f
UH
308 }
309
f800adc4
UH
310 /*
311 * IMPORTANT: PyTuple_SetItem() "steals" a reference to py_value!
2557ad9d 312 * That means we are no longer responsible for Py_XDECREF()'ing it.
f800adc4
UH
313 * It will automatically be free'd when the 'py_args' tuple is free'd.
314 */
6b08da24 315 if (PyTuple_SetItem(py_args, 0, py_value) != 0) { /* STEAL */
036e6f67 316 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
2557ad9d 317 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
036e6f67 318 goto err_run_decref_args;
1c6fa20f
UH
319 }
320
6b08da24 321 if (!(py_res = PyObject_CallObject(py_func, py_args))) { /* NEWREF */
036e6f67
UH
322 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
323 goto err_run_decref_args;
1c6fa20f
UH
324 }
325
036e6f67
UH
326 if ((r = PyObject_AsCharBuffer(py_res, (const char **)outbuf,
327 (Py_ssize_t *)outbuflen))) {
328 ret = SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
2557ad9d 329 Py_XDECREF(py_res);
036e6f67 330 goto err_run_decref_args;
1c6fa20f
UH
331 }
332
036e6f67
UH
333 ret = SIGROKDECODE_OK;
334
2557ad9d 335 Py_XDECREF(py_res);
036e6f67
UH
336
337err_run_decref_args:
2557ad9d 338 Py_XDECREF(py_args);
036e6f67 339err_run_decref_func:
2557ad9d 340 Py_XDECREF(py_func);
2557ad9d 341 Py_XDECREF(py_mod);
1c6fa20f 342
036e6f67
UH
343 if (PyErr_Occurred())
344 PyErr_Print(); /* Returns void. */
345
346 return ret;
1c6fa20f
UH
347}
348
f9b54a6c
UH
349/**
350 * TODO
351 */
352static int sigrokdecode_unload_decoder(struct sigrokdecode_decoder *dec)
353{
354 g_free(dec->id);
355 g_free(dec->name);
356 g_free(dec->desc);
357 g_free(dec->func);
358
359 /* TODO: Free everything in inputformats and outputformats. */
360
361 if (dec->inputformats != NULL)
362 g_slist_free(dec->inputformats);
363 if (dec->outputformats != NULL)
364 g_slist_free(dec->outputformats);
365
366 Py_XDECREF(dec->py_func);
367 Py_XDECREF(dec->py_mod);
368
369 return SIGROKDECODE_OK;
370}
371
372/**
373 * TODO
374 */
375static int sigrokdecode_unload_all_decoders(void)
376{
377 GSList *l;
378 struct sigrokdecode_decoder *dec;
379
380 for (l = sigrokdecode_list_decoders(); l; l = l->next) {
381 dec = l->data;
382 /* TODO: Error handling. */
383 sigrokdecode_unload_decoder(dec);
384 }
385
386 return SIGROKDECODE_OK;
387}
388
1c6fa20f
UH
389/**
390 * Shutdown libsigrokdecode.
391 *
3a9a7e38 392 * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
1c6fa20f
UH
393 */
394int sigrokdecode_shutdown(void)
395{
f9b54a6c
UH
396 /* Unload/free all decoders, and then the list of decoders itself. */
397 /* TODO: Error handling. */
398 sigrokdecode_unload_all_decoders();
399 g_slist_free(list_pds);
400
1c6fa20f
UH
401 /* Py_Finalize() returns void, any finalization errors are ignored. */
402 Py_Finalize();
403
70e44845 404 return SIGROKDECODE_OK;
1c6fa20f 405}