]> sigrok.org Git - libsigrokdecode.git/blob - decode.c
Python decoders: Add more metadata.
[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, "desc", &(d->desc))) < 0)
229                 return r;
230
231         d->py_mod = py_mod;
232
233         Py_XDECREF(py_res);
234         Py_XDECREF(py_func);
235
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. */
241                 Py_XDECREF(py_mod);
242                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
243         }
244
245         d->py_func = py_func;
246
247         /* TODO: Handle func, inputformats, outputformats. */
248         /* Note: They must at least be set to NULL, will segfault otherwise. */
249         d->func = NULL;
250         d->inputformats = NULL;
251         d->outputformats = NULL;
252
253         *dec = d;
254
255         return SRD_OK;
256 }
257
258 /**
259  * Run the specified decoder function.
260  *
261  * @param dec TODO
262  * @param inbuf TODO
263  * @param inbuflen TODO
264  * @param outbuf TODO
265  * @param outbuflen TODO
266  *
267  * @return SRD_OK upon success, a (negative) error code otherwise.
268  */
269 int srd_run_decoder(struct srd_decoder *dec,
270                              uint8_t *inbuf, uint64_t inbuflen,
271                              uint8_t **outbuf, uint64_t *outbuflen)
272 {
273         PyObject *py_mod, *py_func, *py_args, *py_value, *py_res;
274         int r, ret;
275
276         /* TODO: Use #defines for the return codes. */
277
278         /* Return an error upon unusable input. */
279         if (dec == NULL)
280                 return SRD_ERR_ARGS; /* TODO: More specific error? */
281         if (inbuf == NULL)
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? */
285         if (outbuf == NULL)
286                 return SRD_ERR_ARGS; /* TODO: More specific error? */
287         if (outbuflen == NULL)
288                 return SRD_ERR_ARGS; /* TODO: More specific error? */
289
290         /* TODO: Error handling. */
291         py_mod = dec->py_mod;
292         Py_XINCREF(py_mod);
293         py_func = dec->py_func;
294         Py_XINCREF(py_func);
295
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;
300         }
301
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;
307         }
308
309         /*
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.
313          */
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;
318         }
319
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;
323         }
324
325         if ((r = PyObject_AsCharBuffer(py_res, (const char **)outbuf,
326                                       (Py_ssize_t *)outbuflen))) {
327                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
328                 Py_XDECREF(py_res);
329                 goto err_run_decref_args;
330         }
331
332         ret = SRD_OK;
333
334         Py_XDECREF(py_res);
335
336 err_run_decref_args:
337         Py_XDECREF(py_args);
338 err_run_decref_func:
339         Py_XDECREF(py_func);
340         Py_XDECREF(py_mod);
341
342         if (PyErr_Occurred())
343                 PyErr_Print(); /* Returns void. */
344
345         return ret;
346 }
347
348 /**
349  * TODO
350  */
351 static int srd_unload_decoder(struct srd_decoder *dec)
352 {
353         g_free(dec->id);
354         g_free(dec->name);
355         g_free(dec->desc);
356         g_free(dec->func);
357
358         /* TODO: Free everything in inputformats and outputformats. */
359
360         if (dec->inputformats != NULL)
361                 g_slist_free(dec->inputformats);
362         if (dec->outputformats != NULL)
363                 g_slist_free(dec->outputformats);
364
365         Py_XDECREF(dec->py_func);
366         Py_XDECREF(dec->py_mod);
367
368         return SRD_OK;
369 }
370
371 /**
372  * TODO
373  */
374 static int srd_unload_all_decoders(void)
375 {
376         GSList *l;
377         struct srd_decoder *dec;
378
379         for (l = srd_list_decoders(); l; l = l->next) {
380                 dec = l->data;
381                 /* TODO: Error handling. */
382                 srd_unload_decoder(dec);
383         }
384
385         return SRD_OK;
386 }
387
388 /**
389  * Shutdown libsigrokdecode.
390  *
391  * @return SRD_OK upon success, a (negative) error code otherwise.
392  */
393 int srd_exit(void)
394 {
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);
399
400         /* Py_Finalize() returns void, any finalization errors are ignored. */
401         Py_Finalize();
402
403         return SRD_OK;
404 }