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