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