]> sigrok.org Git - libsigrokdecode.git/blob - decode.c
libsigrokdecode: Move decoder metadata into Decoder object.
[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 static 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 static int _unitsize = 1;
53
54 static PyObject*
55 emb_put(PyObject *self, PyObject *args)
56 {
57         PyObject *arg;
58         
59         (void)self;
60
61         if (!PyArg_ParseTuple(args, "O:put", &arg))
62                 return NULL;
63
64         fprintf(stderr, "sigrok.put() called by decoder:\n");
65         PyObject_Print(arg, stdout, Py_PRINT_RAW);
66
67         Py_RETURN_NONE;
68 }
69
70 static PyMethodDef EmbMethods[] = {
71         {"put", emb_put, METH_VARARGS,
72                 "Accepts a dictionary with the following keys: time, duration, data"},
73         {NULL, NULL, 0, NULL}
74 };
75
76 /**
77  * Initialize libsigrokdecode.
78  *
79  * @return SRD_OK upon success, a (negative) error code otherwise.
80  */
81 int srd_init(void)
82 {
83         DIR *dir;
84         struct dirent *dp;
85         char *decodername;
86         struct srd_decoder *dec;
87         int ret;
88
89         /* Py_Initialize() returns void and usually cannot fail. */
90         Py_Initialize();
91
92         Py_InitModule("sigrok", EmbMethods);
93
94         /* Add search directory for the protocol decoders. */
95         /* FIXME: Check error code. */
96         /* FIXME: What happens if this function is called multiple times? */
97         PyRun_SimpleString("import sys;"
98                            "sys.path.append(r'" DECODERS_DIR "');");
99
100         if (!(dir = opendir(DECODERS_DIR)))
101                 return SRD_ERR_DECODERS_DIR;
102
103         while ((dp = readdir(dir)) != NULL) {
104                 if (!g_str_has_suffix(dp->d_name, ".py"))
105                         continue;
106
107                 /* Decoder name == filename (without .py suffix). */
108                 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
109
110                 /* TODO: Error handling. */
111                 dec = malloc(sizeof(struct srd_decoder));
112
113                 /* Load the decoder. */
114                 ret = srd_load_decoder(decodername, &dec);
115                 if (!ret)
116                 {
117                         /* Append it to the list of supported/loaded decoders. */
118                         list_pds = g_slist_append(list_pds, dec);
119                 }
120         }
121         closedir(dir);
122
123         return SRD_OK;
124 }
125
126 /**
127  * Returns the list of supported/loaded protocol decoders.
128  *
129  * This is a GSList containing the names of the decoders as strings.
130  *
131  * @return List of decoders, NULL if none are supported or loaded.
132  */
133 GSList *srd_list_decoders(void)
134 {
135         return list_pds;
136 }
137
138 /**
139  * Get the decoder with the specified ID.
140  *
141  * @param id The ID string of the decoder to return.
142  * @return The decoder with the specified ID, or NULL if not found.
143  */
144 struct srd_decoder *srd_get_decoder_by_id(const char *id)
145 {
146         GSList *l;
147         struct srd_decoder *dec;
148
149         for (l = srd_list_decoders(); l; l = l->next) {
150                 dec = l->data;
151                 if (!strcmp(dec->id, id))
152                         return dec;
153         }
154
155         return NULL;
156 }
157
158 /**
159  * Helper function to handle Python strings.
160  *
161  * TODO: @param entries.
162  *
163  * @return SRD_OK upon success, a (negative) error code otherwise.
164  *         The 'outstr' argument points to a malloc()ed string upon success.
165  */
166 static int h_str(PyObject *py_res, PyObject *py_mod,
167                  const char *key, char **outstr)
168 {
169         PyObject *py_str;
170         char *str;
171         int ret;
172
173         py_str = PyObject_GetAttrString(py_res, (char *)key); /* NEWREF */
174         if (!py_str || !PyString_Check(py_str)) {
175                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
176                 goto err_h_decref_mod;
177         }
178
179         /*
180          * PyString_AsString()'s returned string refers to an internal buffer
181          * (not a copy), i.e. the data must not be modified, and the memory
182          * must not be free()'d.
183          */
184         if (!(str = PyString_AsString(py_str))) {
185                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
186                 goto err_h_decref_str;
187         }
188
189         if (!(*outstr = g_strdup(str))) {
190                 ret = SRD_ERR_MALLOC;
191                 goto err_h_decref_str;
192         }
193
194         Py_XDECREF(py_str);
195
196         return SRD_OK;
197
198 err_h_decref_str:
199         Py_XDECREF(py_str);
200 err_h_decref_mod:
201         Py_XDECREF(py_mod);
202
203         if (PyErr_Occurred())
204                 PyErr_Print(); /* Returns void. */
205
206         return ret;
207 }
208
209 /**
210  * TODO
211  *
212  * @param name TODO
213  *
214  * @return SRD_OK upon success, a (negative) error code otherwise.
215  */
216 static int srd_load_decoder(const char *name,
217                               struct srd_decoder **dec)
218 {
219         struct srd_decoder *d;
220         PyObject *py_mod, *py_res;
221         PyObject *py_args, *py_value, *py_instance;
222         int r;
223         fprintf(stdout, "%s: %s\n", __func__, name);
224
225         /* "Import" the Python module. */
226         if (!(py_mod = PyImport_ImportModule(name))) { /* NEWREF */
227                 PyErr_Print(); /* Returns void. */
228                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
229         }
230
231         /* Get the 'Decoder' class as Python object. */
232         py_res = PyObject_GetAttrString(py_mod, "Decoder"); /* NEWREF */
233         if (!py_res) {
234                 if (PyErr_Occurred())
235                         PyErr_Print(); /* Returns void. */
236                 Py_XDECREF(py_mod);
237                 fprintf(stderr, "Decoder class not found in PD module %s\n", name);
238                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
239         }
240
241         if (!(d = malloc(sizeof(struct srd_decoder))))
242                 return SRD_ERR_MALLOC;
243
244         /* We'll just use the name of the module for the id */
245         d->id = strdup(name);
246
247         if ((r = h_str(py_res, py_mod, "name", &(d->name))) < 0)
248                 return r;
249
250         if ((r = h_str(py_res, py_mod, "longname",
251                        &(d->longname))) < 0)
252                 return r;
253
254         if ((r = h_str(py_res, py_mod, "desc", &(d->desc))) < 0)
255                 return r;
256
257         if ((r = h_str(py_res, py_mod, "longdesc",
258                        &(d->longdesc))) < 0)
259                 return r;
260
261         if ((r = h_str(py_res, py_mod, "author", &(d->author))) < 0)
262                 return r;
263
264         if ((r = h_str(py_res, py_mod, "email", &(d->email))) < 0)
265                 return r;
266
267         if ((r = h_str(py_res, py_mod, "license", &(d->license))) < 0)
268                 return r;
269
270         d->py_mod = py_mod;
271         d->py_decobj = py_res;
272
273         /* Create a Python tuple of size 1. */
274         if (!(py_args = PyTuple_New(0))) { /* NEWREF */
275                 if (PyErr_Occurred())
276                         PyErr_Print(); /* Returns void. */
277                 
278                 Py_XDECREF(py_res);
279                 Py_XDECREF(py_mod);
280                 
281                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
282         }
283         
284         py_value = Py_BuildValue("{sssisd}", 
285                                   "driver", "demo",
286                                   "unitsize", _unitsize, //FIXME: Pass in a unitsize that matches the selected LA
287                                   "starttime", 129318231823.0 //TODO: Fill with something reasonable.
288                                   );
289         /* Create an instance of the Decoder class */
290         py_instance = PyObject_Call(py_res, py_args, py_value);
291         if (!py_instance) {
292                 if (PyErr_Occurred())
293                         PyErr_Print(); /* Returns void. */
294                 Py_XDECREF(py_value); /* TODO: Ref. stolen upon error? */
295                 Py_XDECREF(py_res);
296                 Py_XDECREF(py_mod);
297                 fprintf(stderr, "Unable to create instance of Decoder class in PD module %s\n", name);
298                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
299         } 
300         d->py_instance = py_instance;
301
302         /* TODO: Handle func, inputformats, outputformats. */
303         /* Note: They must at least be set to NULL, will segfault otherwise. */
304         d->func = NULL;
305         d->inputformats = NULL;
306         d->outputformats = NULL;
307
308         *dec = d;
309
310         return SRD_OK;
311 }
312
313 /**
314  * Run the specified decoder function.
315  *
316  * @param dec TODO
317  * @param inbuf TODO
318  * @param inbuflen TODO
319  * @param outbuf TODO
320  * @param outbuflen TODO
321  *
322  * @return SRD_OK upon success, a (negative) error code otherwise.
323  */
324 int srd_run_decoder(struct srd_decoder *dec,
325                              uint8_t *inbuf, uint64_t inbuflen,
326                              uint8_t **outbuf, uint64_t *outbuflen)
327 {
328         PyObject *py_mod, *py_instance, *py_args, *py_value, *py_res;
329         int r, ret;
330         
331         /* FIXME: Don't have a timebase available here. Make one up. */
332         static int _timehack = 0;
333         _timehack += inbuflen;
334
335         /* TODO: Use #defines for the return codes. */
336
337         /* Return an error upon unusable input. */
338         if (dec == NULL)
339                 return SRD_ERR_ARGS; /* TODO: More specific error? */
340         if (inbuf == NULL)
341                 return SRD_ERR_ARGS; /* TODO: More specific error? */
342         if (inbuflen == 0) /* No point in working on empty buffers. */
343                 return SRD_ERR_ARGS; /* TODO: More specific error? */
344         if (outbuf == NULL)
345                 return SRD_ERR_ARGS; /* TODO: More specific error? */
346         if (outbuflen == NULL)
347                 return SRD_ERR_ARGS; /* TODO: More specific error? */
348         
349         /* TODO: Error handling. */
350         py_mod = dec->py_mod;
351         Py_XINCREF(py_mod);
352         py_instance = dec->py_instance;
353         Py_XINCREF(py_instance);
354
355         /* Create a Python tuple of size 1. */
356         if (!(py_args = PyTuple_New(1))) { /* NEWREF */
357                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
358                 goto err_run_decref_func;
359         }
360
361         /* Get the input buffer as Python "string" (byte array). */
362         /* TODO: int vs. uint64_t for 'inbuflen'? */
363
364         py_value = Py_BuildValue("{sisiss#}", 
365                                           "time", _timehack,
366                                           "duration", 10,
367                                           "data", inbuf, inbuflen / _unitsize
368                                           );
369         
370         if (!(py_res = PyObject_CallMethod(py_instance, "decode", 
371                                         "O", py_value))) { /* NEWREF */
372                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
373                 goto err_run_decref_args;
374         }
375
376
377         ret = SRD_OK;
378
379         Py_XDECREF(py_res);
380
381 err_run_decref_args:
382         Py_XDECREF(py_args);
383 err_run_decref_func:
384         Py_XDECREF(py_instance);
385         Py_XDECREF(py_mod);
386
387         if (PyErr_Occurred())
388                 PyErr_Print(); /* Returns void. */
389
390         return ret;
391 }
392
393 /**
394  * TODO
395  */
396 static int srd_unload_decoder(struct srd_decoder *dec)
397 {
398         g_free(dec->id);
399         g_free(dec->name);
400         g_free(dec->desc);
401         g_free(dec->func);
402
403         /* TODO: Free everything in inputformats and outputformats. */
404
405         if (dec->inputformats != NULL)
406                 g_slist_free(dec->inputformats);
407         if (dec->outputformats != NULL)
408                 g_slist_free(dec->outputformats);
409
410         Py_XDECREF(dec->py_instance);
411         Py_XDECREF(dec->py_mod);
412
413         return SRD_OK;
414 }
415
416 /**
417  * TODO
418  */
419 static int srd_unload_all_decoders(void)
420 {
421         GSList *l;
422         struct srd_decoder *dec;
423
424         for (l = srd_list_decoders(); l; l = l->next) {
425                 dec = l->data;
426                 /* TODO: Error handling. */
427                 srd_unload_decoder(dec);
428         }
429
430         return SRD_OK;
431 }
432
433 /**
434  * Shutdown libsigrokdecode.
435  *
436  * @return SRD_OK upon success, a (negative) error code otherwise.
437  */
438 int srd_exit(void)
439 {
440         /* Unload/free all decoders, and then the list of decoders itself. */
441         /* TODO: Error handling. */
442         srd_unload_all_decoders();
443         g_slist_free(list_pds);
444
445         /* Py_Finalize() returns void, any finalization errors are ignored. */
446         Py_Finalize();
447
448         return SRD_OK;
449 }