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