]> sigrok.org Git - libsigrokdecode.git/blob - decode.c
fed9fa790ef75edccade6dcc3f73c80a3e1831f2
[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 PyObject *emb_put(PyObject *self, PyObject *args)
53 {
54         PyObject *arg;
55
56         (void)self;
57
58         if (!PyArg_ParseTuple(args, "O:put", &arg))
59                 return NULL;
60
61         // fprintf(stdout, "sigrok.put() called by decoder:\n");
62         PyObject_Print(arg, stdout, Py_PRINT_RAW);
63         puts("");
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  * This initializes the Python interpreter, and creates and initializes
78  * a "sigrok" Python module with a single put() method.
79  *
80  * Then, it searches for sigrok protocol decoder files (*.py) in the
81  * "decoders" subdirectory of the the sigrok installation directory.
82  * All decoders that are found are loaded into memory and added to an
83  * internal list of decoders, which can be queried via srd_list_decoders().
84  *
85  * The caller is responsible for calling the clean-up function srd_exit(),
86  * which will properly shut down libsigrokdecode and free its allocated memory.
87  *
88  * Multiple calls to srd_init(), without calling srd_exit() inbetween,
89  * are not allowed.
90  *
91  * @return SRD_OK upon success, a (negative) error code otherwise.
92  *         Upon Python errors, return SRD_ERR_PYTHON. If the sigrok decoders
93  *         directory cannot be accessed, return SRD_ERR_DECODERS_DIR.
94  *         If not enough memory could be allocated, return SRD_ERR_MALLOC.
95  */
96 int srd_init(void)
97 {
98         DIR *dir;
99         struct dirent *dp;
100         char *decodername;
101         struct srd_decoder *dec;
102         int ret;
103
104         /* Py_Initialize() returns void and usually cannot fail. */
105         Py_Initialize();
106
107         /* TODO: Use Py_InitModule3() to add a docstring? */
108         if (!Py_InitModule("sigrok", EmbMethods)) {
109                 Py_Finalize(); /* Returns void. */
110                 return SRD_ERR_PYTHON;
111         }
112
113         /* Add search directory for the protocol decoders. */
114         /* FIXME: What happens if this function is called multiple times? */
115         ret = PyRun_SimpleString("import sys;"
116                                  "sys.path.append(r'" DECODERS_DIR "');");
117         if (ret != 0) {
118                 Py_Finalize(); /* Returns void. */
119                 return SRD_ERR_PYTHON;
120         }
121
122         if (!(dir = opendir(DECODERS_DIR))) {
123                 Py_Finalize(); /* Returns void. */
124                 return SRD_ERR_DECODERS_DIR;
125         }
126
127         while ((dp = readdir(dir)) != NULL) {
128                 /* Ignore filenames which don't end with ".py". */
129                 if (!g_str_has_suffix(dp->d_name, ".py"))
130                         continue;
131
132                 /* Decoder name == filename (without .py suffix). */
133                 decodername = g_strndup(dp->d_name, strlen(dp->d_name) - 3);
134
135                 /* TODO: Error handling. Use g_try_malloc(). */
136                 if (!(dec = malloc(sizeof(struct srd_decoder)))) {
137                         Py_Finalize(); /* Returns void. */
138                         return SRD_ERR_MALLOC;
139                 }
140
141                 /* Load the decoder. */
142                 /* TODO: Warning if loading fails for a decoder. */
143                 ret = srd_load_decoder(decodername, &dec);
144                 if (!ret) {
145                         /* Append it to the list of supported/loaded decoders. */
146                         list_pds = g_slist_append(list_pds, dec);
147                 }
148         }
149         closedir(dir);
150
151         return SRD_OK;
152 }
153
154 /**
155  * Returns the list of supported/loaded protocol decoders.
156  *
157  * This is a GSList containing the names of the decoders as strings.
158  *
159  * @return List of decoders, NULL if none are supported or loaded.
160  */
161 GSList *srd_list_decoders(void)
162 {
163         return list_pds;
164 }
165
166 /**
167  * Get the decoder with the specified ID.
168  *
169  * @param id The ID string of the decoder to return.
170  * @return The decoder with the specified ID, or NULL if not found.
171  */
172 struct srd_decoder *srd_get_decoder_by_id(const char *id)
173 {
174         GSList *l;
175         struct srd_decoder *dec;
176
177         for (l = srd_list_decoders(); l; l = l->next) {
178                 dec = l->data;
179                 if (!strcmp(dec->id, id))
180                         return dec;
181         }
182
183         return NULL;
184 }
185
186 /**
187  * Helper function to handle Python strings.
188  *
189  * TODO: @param entries.
190  *
191  * @return SRD_OK upon success, a (negative) error code otherwise.
192  *         The 'outstr' argument points to a malloc()ed string upon success.
193  */
194 static int h_str(PyObject *py_res, PyObject *py_mod,
195                  const char *key, char **outstr)
196 {
197         PyObject *py_str;
198         char *str;
199         int ret;
200
201         py_str = PyObject_GetAttrString(py_res, (char *)key); /* NEWREF */
202         if (!py_str || !PyString_Check(py_str)) {
203                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
204                 goto err_h_decref_mod;
205         }
206
207         /*
208          * PyString_AsString()'s returned string refers to an internal buffer
209          * (not a copy), i.e. the data must not be modified, and the memory
210          * must not be free()'d.
211          */
212         if (!(str = PyString_AsString(py_str))) {
213                 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
214                 goto err_h_decref_str;
215         }
216
217         if (!(*outstr = g_strdup(str))) {
218                 ret = SRD_ERR_MALLOC;
219                 goto err_h_decref_str;
220         }
221
222         Py_XDECREF(py_str);
223
224         return SRD_OK;
225
226 err_h_decref_str:
227         Py_XDECREF(py_str);
228 err_h_decref_mod:
229         Py_XDECREF(py_mod);
230
231         if (PyErr_Occurred())
232                 PyErr_Print(); /* Returns void. */
233
234         return ret;
235 }
236
237 /**
238  * TODO
239  *
240  * @param name TODO
241  *
242  * @return SRD_OK upon success, a (negative) error code otherwise.
243  */
244 static int srd_load_decoder(const char *name, struct srd_decoder **dec)
245 {
246         struct srd_decoder *d;
247         PyObject *py_mod, *py_res;
248         int r;
249
250         fprintf(stdout, "%s: %s\n", __func__, name);
251
252         /* "Import" the Python module. */
253         if (!(py_mod = PyImport_ImportModule(name))) { /* NEWREF */
254                 PyErr_Print(); /* Returns void. */
255                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
256         }
257
258         /* Get the 'Decoder' class as Python object. */
259         py_res = PyObject_GetAttrString(py_mod, "Decoder"); /* NEWREF */
260         if (!py_res) {
261                 if (PyErr_Occurred())
262                         PyErr_Print(); /* Returns void. */
263                 Py_XDECREF(py_mod);
264                 fprintf(stderr, "Decoder class not found in PD module %s\n", name);
265                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
266         }
267
268         if (!(d = malloc(sizeof(struct srd_decoder))))
269                 return SRD_ERR_MALLOC;
270
271         /* We'll just use the name of the module for the ID. */
272         d->id = strdup(name);
273
274         if ((r = h_str(py_res, py_mod, "name", &(d->name))) < 0)
275                 return r;
276
277         if ((r = h_str(py_res, py_mod, "longname",
278                        &(d->longname))) < 0)
279                 return r;
280
281         if ((r = h_str(py_res, py_mod, "desc", &(d->desc))) < 0)
282                 return r;
283
284         if ((r = h_str(py_res, py_mod, "longdesc",
285                        &(d->longdesc))) < 0)
286                 return r;
287
288         if ((r = h_str(py_res, py_mod, "author", &(d->author))) < 0)
289                 return r;
290
291         if ((r = h_str(py_res, py_mod, "email", &(d->email))) < 0)
292                 return r;
293
294         if ((r = h_str(py_res, py_mod, "license", &(d->license))) < 0)
295                 return r;
296
297         d->py_mod = py_mod;
298         d->py_decobj = py_res;
299
300         /* TODO: Handle func, inputformats, outputformats. */
301         /* Note: They must at least be set to NULL, will segfault otherwise. */
302         d->func = NULL;
303         d->inputformats = NULL;
304         d->outputformats = NULL;
305
306         *dec = d;
307
308         return SRD_OK;
309 }
310
311 struct srd_decoder_instance *srd_instance_new(const char *id)
312 {
313         struct srd_decoder *dec;
314         struct srd_decoder_instance *di;
315         PyObject *py_args;
316
317         if (!(dec = srd_get_decoder_by_id(id)))
318                 return NULL;
319
320         /* TODO: Error handling. Use g_try_malloc(). */
321         di = g_malloc(sizeof(*di));
322
323         /* Create an empty Python tuple. */
324         if (!(py_args = PyTuple_New(0))) { /* NEWREF */
325                 if (PyErr_Occurred())
326                         PyErr_Print(); /* Returns void. */
327
328                 return NULL; /* TODO: More specific error? */
329         }
330
331         /* Create an instance of the 'Decoder' class. */
332         di->py_instance = PyObject_Call(dec->py_decobj, py_args, NULL);
333         if (!di->py_instance) {
334                 if (PyErr_Occurred())
335                         PyErr_Print(); /* Returns void. */
336                 Py_XDECREF(py_args);
337                 return NULL; /* TODO: More specific error? */
338         }
339
340         Py_XDECREF(py_args);
341
342         return di;
343 }
344
345 int srd_instance_set_probe(struct srd_decoder_instance *di,
346                            const char *probename, int num)
347 {
348         PyObject *probedict, *probenum;
349
350         probedict = PyObject_GetAttrString(di->py_instance, "probes"); /* NEWREF */
351         if (!probedict) {
352                 if (PyErr_Occurred())
353                         PyErr_Print(); /* Returns void. */
354
355                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
356         }
357
358         probenum = PyInt_FromLong(num);
359         PyMapping_SetItemString(probedict, (char *)probename, probenum);
360
361         Py_XDECREF(probenum);
362         Py_XDECREF(probedict);
363
364         return SRD_OK;
365 }
366
367 int srd_instance_start(struct srd_decoder_instance *di,
368                         const char *driver, int unitsize, uint64_t starttime,
369                         uint64_t samplerate)
370 {
371         PyObject *py_res;
372
373         if (!(py_res = PyObject_CallMethod(di->py_instance, "start",
374                                          "{s:s,s:l,s:l,s:l}", 
375                                          "driver", driver,
376                                          "unitsize", (long)unitsize,
377                                          "starttime", (long)starttime,
378                                          "samplerate", (long)samplerate))) {
379                 if (PyErr_Occurred())
380                         PyErr_Print(); /* Returns void. */
381
382                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
383         }
384         Py_XDECREF(py_res);
385         return SRD_OK;
386 }
387
388 /**
389  * Run the specified decoder function.
390  *
391  * @param dec TODO
392  * @param inbuf TODO
393  * @param inbuflen TODO
394  * @param outbuf TODO
395  * @param outbuflen TODO
396  *
397  * @return SRD_OK upon success, a (negative) error code otherwise.
398  */
399 int srd_run_decoder(struct srd_decoder_instance *dec,
400                     uint8_t *inbuf, uint64_t inbuflen,
401                     uint8_t **outbuf, uint64_t *outbuflen)
402 {
403         PyObject *py_instance, *py_res;
404         /* FIXME: Don't have a timebase available here. Make one up. */
405         static int _timehack = 0;
406
407         _timehack += inbuflen;
408
409         /* TODO: Use #defines for the return codes. */
410
411         /* Return an error upon unusable input. */
412         if (dec == NULL)
413                 return SRD_ERR_ARGS; /* TODO: More specific error? */
414         if (inbuf == NULL)
415                 return SRD_ERR_ARGS; /* TODO: More specific error? */
416         if (inbuflen == 0) /* No point in working on empty buffers. */
417                 return SRD_ERR_ARGS; /* TODO: More specific error? */
418         if (outbuf == NULL)
419                 return SRD_ERR_ARGS; /* TODO: More specific error? */
420         if (outbuflen == NULL)
421                 return SRD_ERR_ARGS; /* TODO: More specific error? */
422
423         /* TODO: Error handling. */
424         py_instance = dec->py_instance;
425         Py_XINCREF(py_instance);
426
427         if (!(py_res = PyObject_CallMethod(py_instance, "decode",
428                                            "{s:i,s:i,s:s#}", 
429                                            "time", _timehack,
430                                            "duration", 10,
431                                            "data", inbuf, inbuflen))) { /* NEWREF */
432                 if (PyErr_Occurred())
433                         PyErr_Print(); /* Returns void. */
434
435                 return SRD_ERR_PYTHON; /* TODO: More specific error? */
436         } 
437
438         Py_XDECREF(py_res);
439         return SRD_OK;
440 }
441
442 /**
443  * TODO
444  */
445 static int srd_unload_decoder(struct srd_decoder *dec)
446 {
447         g_free(dec->id);
448         g_free(dec->name);
449         g_free(dec->desc);
450         g_free(dec->func);
451
452         /* TODO: Free everything in inputformats and outputformats. */
453
454         if (dec->inputformats != NULL)
455                 g_slist_free(dec->inputformats);
456         if (dec->outputformats != NULL)
457                 g_slist_free(dec->outputformats);
458
459         Py_XDECREF(dec->py_decobj);
460         Py_XDECREF(dec->py_mod);
461
462         /* TODO: (g_)free dec itself? */
463
464         return SRD_OK;
465 }
466
467 /**
468  * TODO
469  */
470 static int srd_unload_all_decoders(void)
471 {
472         GSList *l;
473         struct srd_decoder *dec;
474
475         for (l = srd_list_decoders(); l; l = l->next) {
476                 dec = l->data;
477                 /* TODO: Error handling. */
478                 srd_unload_decoder(dec);
479         }
480
481         return SRD_OK;
482 }
483
484 /**
485  * Shutdown libsigrokdecode.
486  *
487  * This frees all the memory allocated for protocol decoders and shuts down
488  * the Python interpreter.
489  *
490  * This function should only be called if there was a (successful!) invocation
491  * of srd_init() before. Calling this function multiple times in a row, without
492  * any successful srd_init() calls inbetween, is not allowed.
493  *
494  * @return SRD_OK upon success, a (negative) error code otherwise.
495  */
496 int srd_exit(void)
497 {
498         /* Unload/free all decoders, and then the list of decoders itself. */
499         /* TODO: Error handling. */
500         srd_unload_all_decoders();
501         g_slist_free(list_pds);
502
503         /* Py_Finalize() returns void, any finalization errors are ignored. */
504         Py_Finalize();
505
506         return SRD_OK;
507 }