]> sigrok.org Git - libsigrokdecode.git/blob - decode.c
c2beab29a6bc619fbb783aae3d2d14db2d3f8858
[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 <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include <stdio.h>
23 #include <string.h>
24 #include <dirent.h>
25 #include <config.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 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_DECREF() it.
43  *
44  *  - If it returns a "borrowed reference", you MUST NOT Py_DECREF() it.
45  *
46  *  - If a function "steals" a reference, you no longer are responsible for
47  *    Py_DECREF()ing it (someone else will do it for you at some point).
48  */
49
50 /**
51  * Initialize libsigrokdecode.
52  *
53  * @return SIGROKDECODE_OK upon success, a (negative) error code otherwise.
54  */
55 int sigrokdecode_init(void)
56 {
57         DIR *dir;
58         struct dirent *dp;
59         char *tmp;
60
61         /* Py_Initialize() returns void and usually cannot fail. */
62         Py_Initialize();
63
64         /* Add search directory for the protocol decoders. */
65         /* FIXME: Check error code. */
66         /* FIXME: What happens if this function is called multiple times? */
67         PyRun_SimpleString("import sys;"
68                            "sys.path.append(r'" DECODERS_DIR "');");
69
70         if (!(dir = opendir(DECODERS_DIR)))
71                 return SIGROKDECODE_ERR_DECODERS_DIR;
72
73         while ((dp = readdir(dir)) != NULL) {
74                 if (!g_str_has_suffix(dp->d_name, ".py"))
75                         continue;
76                 /* For now use the filename (without .py) as decoder name. */
77                 if ((tmp = g_strndup(dp->d_name, strlen(dp->d_name) - 3)))
78                         list_pds = g_slist_append(list_pds, tmp);
79         }
80         closedir(dir);
81
82         return SIGROKDECODE_OK;
83 }
84
85 /**
86  * Returns the list of supported/loaded protocol decoders.
87  *
88  * This is a GSList containing the names of the decoders as strings.
89  *
90  * @return List of decoders, NULL if none are supported or loaded.
91  */
92 GSList *sigrokdecode_list_decoders(void)
93 {
94         return list_pds;
95 }
96
97 /**
98  * Helper function to handle Python strings.
99  *
100  * TODO: @param entries.
101  *
102  * @return LIBSIGROKDECODE_OK upon success, a (negative) error code otherwise.
103  *         The 'outstr' argument points to a malloc()ed string upon success.
104  */
105 static int h_str(PyObject *py_res, PyObject *py_func, PyObject *py_mod,
106                  const char *key, char **outstr)
107 {
108         PyObject *py_str;
109         char *str;
110
111         py_str = PyMapping_GetItemString(py_res, (char *)key);
112         if (!py_str || !PyString_Check(py_str)) {
113                 if (PyErr_Occurred())
114                         PyErr_Print();
115                 Py_DECREF(py_func);
116                 Py_DECREF(py_mod);
117                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
118         }
119
120         if (!(str = PyString_AsString(py_str))) {
121                 if (PyErr_Occurred())
122                         PyErr_Print();
123                 Py_DECREF(py_str);
124                 Py_DECREF(py_func);
125                 Py_DECREF(py_mod);
126                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
127         }
128
129         if (!(*outstr = strdup(str))) {
130                 if (PyErr_Occurred())
131                         PyErr_Print();
132                 Py_DECREF(py_str);
133                 Py_DECREF(py_func);
134                 Py_DECREF(py_mod);
135                 return SIGROKDECODE_ERR_MALLOC;
136         }
137
138         Py_DECREF(py_str);
139
140         return SIGROKDECODE_OK;
141 }
142
143 /**
144  * TODO
145  *
146  * @param name TODO
147  *
148  * @return LIBSIGROKDECODE_OK upon success, a (negative) error code otherwise.
149  */
150 int sigrokdecode_load_decoder(const char *name,
151                               struct sigrokdecode_decoder **dec)
152 {
153         struct sigrokdecode_decoder *d;
154         PyObject *py_name, *py_mod, *py_func, *py_res /* , *py_tuple */;
155         int r;
156
157         /* Get the name of the decoder module as Python string. */
158         if (!(py_name = PyString_FromString(name))) {
159                 PyErr_Print();
160                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
161         }
162
163         /* "Import" the Python module. */
164         if (!(py_mod = PyImport_Import(py_name))) {
165                 PyErr_Print();
166                 Py_DECREF(py_name);
167                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
168         }
169         Py_DECREF(py_name);
170
171         /* Get the 'register' function name as Python callable object. */
172         py_func = PyObject_GetAttrString(py_mod, "register");
173         if (!py_func || !PyCallable_Check(py_func)) {
174                 if (PyErr_Occurred())
175                         PyErr_Print();
176                 Py_DECREF(py_mod);
177                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
178         }
179
180         /* Call the 'register' function without arguments, get the result. */
181         if (!(py_res = PyObject_CallFunction(py_func, NULL))) {
182                 PyErr_Print();
183                 Py_DECREF(py_func);
184                 Py_DECREF(py_mod);
185                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
186         }
187
188         if (!(d = malloc(sizeof(struct sigrokdecode_decoder))))
189                 return SIGROKDECODE_ERR_MALLOC;
190
191         if ((r = h_str(py_res, py_func, py_mod, "id", &(d->id))) < 0)
192                 return r;
193
194         if ((r = h_str(py_res, py_func, py_mod, "name", &(d->name))) < 0)
195                 return r;
196
197         if ((r = h_str(py_res, py_func, py_mod, "desc", &(d->desc))) < 0)
198                 return r;
199
200         d->py_mod = py_mod;
201
202         Py_DECREF(py_res);
203         Py_DECREF(py_func);
204
205         /* Get the 'decode' function name as Python callable object. */
206         py_func = PyObject_GetAttrString(py_mod, "decode");
207         if (!py_func || !PyCallable_Check(py_func)) {
208                 if (PyErr_Occurred())
209                         PyErr_Print();
210                 Py_DECREF(py_mod);
211                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
212         }
213
214         d->py_func = py_func;
215
216         /* TODO: Handle inputformats, outputformats. */
217
218         *dec = d;
219
220         return SIGROKDECODE_OK;
221 }
222
223 /**
224  * Run the specified decoder function.
225  *
226  * @param dec TODO
227  * @param inbuf TODO
228  * @param inbuflen TODO
229  * @param outbuf TODO
230  * @param outbuflen TODO
231  *
232  * @return LIBSIGROKDECODE_OK upon success, a (negative) error code otherwise.
233  */
234 int sigrokdecode_run_decoder(struct sigrokdecode_decoder *dec,
235                              uint8_t *inbuf, uint64_t inbuflen,
236                              uint8_t **outbuf, uint64_t *outbuflen)
237 {
238         PyObject *py_mod, *py_func, *py_args, *py_value, *py_res;
239         int ret;
240
241         /* TODO: Use #defines for the return codes. */
242
243         /* Return an error upon unusable input. */
244         if (dec == NULL)
245                 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
246         if (inbuf == NULL)
247                 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
248         if (inbuflen == 0) /* No point in working on empty buffers. */
249                 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
250         if (outbuf == NULL)
251                 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
252         if (outbuflen == NULL)
253                 return SIGROKDECODE_ERR_ARGS; /* TODO: More specific error? */
254
255         /* TODO: Error handling. */
256         py_mod = dec->py_mod;
257         py_func = dec->py_func;
258
259         /* TODO: Really run Py_DECREF on py_mod/py_func? */
260
261         /* Create a Python tuple of size 1. */
262         if (!(py_args = PyTuple_New(1))) {
263                 PyErr_Print();
264                 Py_DECREF(py_func);
265                 Py_DECREF(py_mod);
266                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
267         }
268
269         /* Get the input buffer as Python "string" (byte array). */
270         /* TODO: int vs. uint64_t for 'inbuflen'? */
271         if (!(py_value = Py_BuildValue("s#", inbuf, inbuflen))) {
272                 PyErr_Print();
273                 Py_DECREF(py_args);
274                 Py_DECREF(py_func);
275                 Py_DECREF(py_mod);
276                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
277         }
278
279         /*
280          * IMPORTANT: PyTuple_SetItem() "steals" a reference to py_value!
281          * That means we are no longer responsible for Py_DECREF()'ing it.
282          * It will automatically be free'd when the 'py_args' tuple is free'd.
283          */
284         if (PyTuple_SetItem(py_args, 0, py_value) != 0) {
285                 PyErr_Print();
286                 Py_DECREF(py_value); /* TODO: Ref. stolen upon error? */
287                 Py_DECREF(py_args);
288                 Py_DECREF(py_func);
289                 Py_DECREF(py_mod);
290                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
291         }
292
293         if (!(py_res = PyObject_CallObject(py_func, py_args))) {
294                 PyErr_Print();
295                 Py_DECREF(py_args);
296                 Py_DECREF(py_func);
297                 Py_DECREF(py_mod);
298                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
299         }
300
301         if ((ret = PyObject_AsCharBuffer(py_res, (const char **)outbuf,
302                                          (Py_ssize_t *)outbuflen))) {
303                 PyErr_Print();
304                 Py_DECREF(py_res);
305                 Py_DECREF(py_args);
306                 Py_DECREF(py_func);
307                 Py_DECREF(py_mod);
308                 return SIGROKDECODE_ERR_PYTHON; /* TODO: More specific error? */
309         }
310
311         Py_DECREF(py_res);
312         Py_DECREF(py_args);
313         Py_DECREF(py_func);
314         Py_DECREF(py_mod);
315
316         return SIGROKDECODE_OK;
317 }
318
319 /**
320  * Shutdown libsigrokdecode.
321  *
322  * @return LIBSIGROKDECODE_OK upon success, a (negative) error code otherwise.
323  */
324 int sigrokdecode_shutdown(void)
325 {
326         /* Py_Finalize() returns void, any finalization errors are ignored. */
327         Py_Finalize();
328
329         return SIGROKDECODE_OK;
330 }