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