]> sigrok.org Git - libsigrokdecode.git/blob - decode.c
Add doxygen config files for both libs.
[libsigrokdecode.git] / decode.c
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 "config.h"
22 #include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include <stdio.h>
24 #include <string.h>
25 #include <dirent.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. */
35 GSList *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 static int srd_load_decoder(const char *name, struct srd_decoder **dec);
51
52 /**
53  * Initialize libsigrokdecode.
54  *
55  * @return SRD_OK upon success, a (negative) error code otherwise.
56  */
57 int srd_init(void)
58 {
59         DIR *dir;
60         struct dirent *dp;
61         char *decodername;
62         struct srd_decoder *dec;
63         int ret;
64
65         /* Py_Initialize() returns void and usually cannot fail. */
66         Py_Initialize();
67
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 "');");
73
74         if (!(dir = opendir(DECODERS_DIR)))
75                 return SRD_ERR_DECODERS_DIR;
76
77         while ((dp = readdir(dir)) != NULL) {
78                 if (!g_str_has_suffix(dp->d_name, ".py"))
79                         continue;
80
81                 /* Decoder name == filename (without .py suffix). */
82                 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
83
84                 /* TODO: Error handling. */
85                 dec = malloc(sizeof(struct srd_decoder));
86
87                 /* Load the decoder. */
88                 ret = srd_load_decoder(decodername, &dec);
89
90                 /* Append it to the list of supported/loaded decoders. */
91                 list_pds = g_slist_append(list_pds, dec);
92         }
93         closedir(dir);
94
95         return SRD_OK;
96 }
97
98 /**
99  * Returns the list of supported/loaded protocol decoders.
100  *
101  * This is a GSList containing the names of the decoders as strings.
102  *
103  * @return List of decoders, NULL if none are supported or loaded.
104  */
105 GSList *srd_list_decoders(void)
106 {
107         return list_pds;
108 }
109
110 /**
111  * Get the decoder with the specified ID.
112  *
113  * @param id The ID string of the decoder to return.
114  * @return The decoder with the specified ID, or NULL if not found.
115  */
116 struct srd_decoder *srd_get_decoder_by_id(const char *id)
117 {
118         GSList *l;
119         struct srd_decoder *dec;
120
121         for (l = srd_list_decoders(); l; l = l->next) {
122                 dec = l->data;
123                 if (!strcmp(dec->id, id))
124                         return dec;
125         }
126
127         return NULL;
128 }
129
130 /**
131  * Helper function to handle Python strings.
132  *
133  * TODO: @param entries.
134  *
135  * @return SRD_OK upon success, a (negative) error code otherwise.
136  *         The 'outstr' argument points to a malloc()ed string upon success.
137  */
138 static int h_str(PyObject *py_res, PyObject *py_func, PyObject *py_mod,
139                  const char *key, char **outstr)
140 {
141         PyObject *py_str;
142         char *str;
143         int ret;
144
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;
149         }
150
151         /*
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.
155          */
156         if (!(str = PyString_AsString(py_str))) {
157                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
158                 goto err_h_decref_str;
159         }
160
161         if (!(*outstr = g_strdup(str))) {
162                 ret = SRD_ERR_MALLOC;
163                 goto err_h_decref_str;
164         }
165
166         Py_XDECREF(py_str);
167
168         return SRD_OK;
169
170 err_h_decref_str:
171         Py_XDECREF(py_str);
172 err_h_decref_func:
173         Py_XDECREF(py_func);
174         Py_XDECREF(py_mod);
175
176         if (PyErr_Occurred())
177                 PyErr_Print(); /* Returns void. */
178
179         return ret;
180 }
181
182 /**
183  * TODO
184  *
185  * @param name TODO
186  *
187  * @return SRD_OK upon success, a (negative) error code otherwise.
188  */
189 static int srd_load_decoder(const char *name,
190                               struct srd_decoder **dec)
191 {
192         struct srd_decoder *d;
193         PyObject *py_mod, *py_func, *py_res /* , *py_tuple */;
194         int r;
195
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? */
200         }
201
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. */
207                 Py_XDECREF(py_mod);
208                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
209         }
210
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. */
214                 Py_XDECREF(py_func);
215                 Py_XDECREF(py_mod);
216                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
217         }
218
219         if (!(d = malloc(sizeof(struct srd_decoder))))
220                 return SRD_ERR_MALLOC;
221
222         if ((r = h_str(py_res, py_func, py_mod, "id", &(d->id))) < 0)
223                 return r;
224
225         if ((r = h_str(py_res, py_func, py_mod, "name", &(d->name))) < 0)
226                 return r;
227
228         if ((r = h_str(py_res, py_func, py_mod, "longname",
229                        &(d->longname))) < 0)
230                 return r;
231
232         if ((r = h_str(py_res, py_func, py_mod, "desc", &(d->desc))) < 0)
233                 return r;
234
235         if ((r = h_str(py_res, py_func, py_mod, "longdesc",
236                        &(d->longdesc))) < 0)
237                 return r;
238
239         if ((r = h_str(py_res, py_func, py_mod, "author", &(d->author))) < 0)
240                 return r;
241
242         if ((r = h_str(py_res, py_func, py_mod, "email", &(d->email))) < 0)
243                 return r;
244
245         if ((r = h_str(py_res, py_func, py_mod, "license", &(d->license))) < 0)
246                 return r;
247
248         d->py_mod = py_mod;
249
250         Py_XDECREF(py_res);
251         Py_XDECREF(py_func);
252
253         /* Get the 'decode' function name as Python callable object. */
254         py_func = PyObject_GetAttrString(py_mod, "decode"); /* NEWREF */
255         if (!py_func || !PyCallable_Check(py_func)) {
256                 if (PyErr_Occurred())
257                         PyErr_Print(); /* Returns void. */
258                 Py_XDECREF(py_mod);
259                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
260         }
261
262         d->py_func = py_func;
263
264         /* TODO: Handle func, inputformats, outputformats. */
265         /* Note: They must at least be set to NULL, will segfault otherwise. */
266         d->func = NULL;
267         d->inputformats = NULL;
268         d->outputformats = NULL;
269
270         *dec = d;
271
272         return SRD_OK;
273 }
274
275 /**
276  * Run the specified decoder function.
277  *
278  * @param dec TODO
279  * @param inbuf TODO
280  * @param inbuflen TODO
281  * @param outbuf TODO
282  * @param outbuflen TODO
283  *
284  * @return SRD_OK upon success, a (negative) error code otherwise.
285  */
286 int srd_run_decoder(struct srd_decoder *dec,
287                              uint8_t *inbuf, uint64_t inbuflen,
288                              uint8_t **outbuf, uint64_t *outbuflen)
289 {
290         PyObject *py_mod, *py_func, *py_args, *py_value, *py_res;
291         int r, ret;
292
293         /* TODO: Use #defines for the return codes. */
294
295         /* Return an error upon unusable input. */
296         if (dec == NULL)
297                 return SRD_ERR_ARGS; /* TODO: More specific error? */
298         if (inbuf == NULL)
299                 return SRD_ERR_ARGS; /* TODO: More specific error? */
300         if (inbuflen == 0) /* No point in working on empty buffers. */
301                 return SRD_ERR_ARGS; /* TODO: More specific error? */
302         if (outbuf == NULL)
303                 return SRD_ERR_ARGS; /* TODO: More specific error? */
304         if (outbuflen == NULL)
305                 return SRD_ERR_ARGS; /* TODO: More specific error? */
306
307         /* TODO: Error handling. */
308         py_mod = dec->py_mod;
309         Py_XINCREF(py_mod);
310         py_func = dec->py_func;
311         Py_XINCREF(py_func);
312
313         /* Create a Python tuple of size 1. */
314         if (!(py_args = PyTuple_New(1))) { /* NEWREF */
315                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
316                 goto err_run_decref_func;
317         }
318
319         /* Get the input buffer as Python "string" (byte array). */
320         /* TODO: int vs. uint64_t for 'inbuflen'? */
321         if (!(py_value = Py_BuildValue("s#", inbuf, inbuflen))) { /* NEWREF */
322                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
323                 goto err_run_decref_args;
324         }
325
326         /*
327          * IMPORTANT: PyTuple_SetItem() "steals" a reference to py_value!
328          * That means we are no longer responsible for Py_XDECREF()'ing it.
329          * It will automatically be free'd when the 'py_args' tuple is free'd.
330          */
331         if (PyTuple_SetItem(py_args, 0, py_value) != 0) { /* STEAL */
332                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
333                 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
334                 goto err_run_decref_args;
335         }
336
337         if (!(py_res = PyObject_CallObject(py_func, py_args))) { /* NEWREF */
338                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
339                 goto err_run_decref_args;
340         }
341
342         if ((r = PyObject_AsCharBuffer(py_res, (const char **)outbuf,
343                                       (Py_ssize_t *)outbuflen))) {
344                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
345                 Py_XDECREF(py_res);
346                 goto err_run_decref_args;
347         }
348
349         ret = SRD_OK;
350
351         Py_XDECREF(py_res);
352
353 err_run_decref_args:
354         Py_XDECREF(py_args);
355 err_run_decref_func:
356         Py_XDECREF(py_func);
357         Py_XDECREF(py_mod);
358
359         if (PyErr_Occurred())
360                 PyErr_Print(); /* Returns void. */
361
362         return ret;
363 }
364
365 /**
366  * TODO
367  */
368 static int srd_unload_decoder(struct srd_decoder *dec)
369 {
370         g_free(dec->id);
371         g_free(dec->name);
372         g_free(dec->desc);
373         g_free(dec->func);
374
375         /* TODO: Free everything in inputformats and outputformats. */
376
377         if (dec->inputformats != NULL)
378                 g_slist_free(dec->inputformats);
379         if (dec->outputformats != NULL)
380                 g_slist_free(dec->outputformats);
381
382         Py_XDECREF(dec->py_func);
383         Py_XDECREF(dec->py_mod);
384
385         return SRD_OK;
386 }
387
388 /**
389  * TODO
390  */
391 static int srd_unload_all_decoders(void)
392 {
393         GSList *l;
394         struct srd_decoder *dec;
395
396         for (l = srd_list_decoders(); l; l = l->next) {
397                 dec = l->data;
398                 /* TODO: Error handling. */
399                 srd_unload_decoder(dec);
400         }
401
402         return SRD_OK;
403 }
404
405 /**
406  * Shutdown libsigrokdecode.
407  *
408  * @return SRD_OK upon success, a (negative) error code otherwise.
409  */
410 int srd_exit(void)
411 {
412         /* Unload/free all decoders, and then the list of decoders itself. */
413         /* TODO: Error handling. */
414         srd_unload_all_decoders();
415         g_slist_free(list_pds);
416
417         /* Py_Finalize() returns void, any finalization errors are ignored. */
418         Py_Finalize();
419
420         return SRD_OK;
421 }