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