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