]> sigrok.org Git - libsigrokdecode.git/blob - util.c
avr_isp: Add more parts
[libsigrokdecode.git] / util.c
1 /*
2  * This file is part of the libsigrokdecode project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23
24 /**
25  * Import a Python module by name.
26  *
27  * This function is implemented in terms of PyImport_Import() rather than
28  * PyImport_ImportModule(), so that the import hooks are not bypassed.
29  *
30  * @param[in] name The name of the module to load as UTF-8 string.
31  * @return The Python module object, or NULL if an exception occurred. The
32  *  caller is responsible for evaluating and clearing the Python error state.
33  *
34  * @private
35  */
36 SRD_PRIV PyObject *py_import_by_name(const char *name)
37 {
38         PyObject *py_mod, *py_modname;
39         PyGILState_STATE gstate;
40
41         gstate = PyGILState_Ensure();
42
43         py_modname = PyUnicode_FromString(name);
44         if (!py_modname) {
45                 PyGILState_Release(gstate);
46                 return NULL;
47         }
48
49         py_mod = PyImport_Import(py_modname);
50         Py_DECREF(py_modname);
51
52         PyGILState_Release(gstate);
53
54         return py_mod;
55 }
56
57 /**
58  * Get the value of a Python object's attribute, returned as a newly
59  * allocated char *.
60  *
61  * @param[in] py_obj The object to probe.
62  * @param[in] attr Name of the attribute to retrieve.
63  * @param[out] outstr ptr to char * storage to be filled in.
64  *
65  * @return SRD_OK upon success, a (negative) error code otherwise.
66  *         The 'outstr' argument points to a g_malloc()ed string upon success.
67  *
68  * @private
69  */
70 SRD_PRIV int py_attr_as_str(PyObject *py_obj, const char *attr, char **outstr)
71 {
72         PyObject *py_str;
73         int ret;
74         PyGILState_STATE gstate;
75
76         gstate = PyGILState_Ensure();
77
78         if (!PyObject_HasAttrString(py_obj, attr)) {
79                 srd_dbg("Object has no attribute '%s'.", attr);
80                 goto err;
81         }
82
83         if (!(py_str = PyObject_GetAttrString(py_obj, attr))) {
84                 srd_exception_catch("Failed to get attribute '%s'", attr);
85                 goto err;
86         }
87
88         ret = py_str_as_str(py_str, outstr);
89         Py_DECREF(py_str);
90
91         PyGILState_Release(gstate);
92
93         return ret;
94
95 err:
96         PyGILState_Release(gstate);
97
98         return SRD_ERR_PYTHON;
99 }
100
101 /**
102  * Get the value of a Python object's attribute, returned as a newly
103  * allocated GSList of char *.
104  *
105  * @param[in] py_obj The object to probe.
106  * @param[in] attr Name of the attribute to retrieve.
107  * @param[out] outstrlist ptr to GSList of char * storage to be filled in.
108  *
109  * @return SRD_OK upon success, a (negative) error code otherwise.
110  *         The 'outstrlist' argument points to a GSList of g_malloc()ed strings
111  *         upon success.
112  *
113  * @private
114  */
115 SRD_PRIV int py_attr_as_strlist(PyObject *py_obj, const char *attr, GSList **outstrlist)
116 {
117         PyObject *py_list;
118         ssize_t idx;
119         int ret;
120         char *outstr;
121         PyGILState_STATE gstate;
122
123         gstate = PyGILState_Ensure();
124
125         if (!PyObject_HasAttrString(py_obj, attr)) {
126                 srd_dbg("Object has no attribute '%s'.", attr);
127                 goto err;
128         }
129
130         if (!(py_list = PyObject_GetAttrString(py_obj, attr))) {
131                 srd_exception_catch("Failed to get attribute '%s'", attr);
132                 goto err;
133         }
134
135         if (!PyList_Check(py_list)) {
136                 srd_dbg("Object is not a list.");
137                 goto err;
138         }
139
140         *outstrlist = NULL;
141
142         for (idx = 0; idx < PyList_Size(py_list); idx++) {
143                 ret = py_listitem_as_str(py_list, idx, &outstr);
144                 if (ret < 0) {
145                         srd_dbg("Couldn't get item %zd.", idx);
146                         goto err;
147                 }
148                 *outstrlist = g_slist_append(*outstrlist, outstr);
149         }
150
151         Py_DECREF(py_list);
152
153         PyGILState_Release(gstate);
154
155         return SRD_OK;
156
157 err:
158         PyGILState_Release(gstate);
159
160         return SRD_ERR_PYTHON;
161 }
162
163 /**
164  * Get the value of a Python dictionary item, returned as a newly
165  * allocated char *.
166  *
167  * @param[in] py_obj The dictionary to probe.
168  * @param[in] key Key of the item to retrieve.
169  * @param[out] outstr Pointer to char * storage to be filled in.
170  *
171  * @return SRD_OK upon success, a (negative) error code otherwise.
172  *         The 'outstr' argument points to a g_malloc()ed string upon success.
173  *
174  * @private
175  */
176 SRD_PRIV int py_dictitem_as_str(PyObject *py_obj, const char *key,
177                                 char **outstr)
178 {
179         PyObject *py_value;
180         PyGILState_STATE gstate;
181
182         gstate = PyGILState_Ensure();
183
184         if (!PyDict_Check(py_obj)) {
185                 srd_dbg("Object is not a dictionary.");
186                 goto err;
187         }
188
189         if (!(py_value = PyDict_GetItemString(py_obj, key))) {
190                 srd_dbg("Dictionary has no attribute '%s'.", key);
191                 goto err;
192         }
193
194         PyGILState_Release(gstate);
195
196         return py_str_as_str(py_value, outstr);
197
198 err:
199         PyGILState_Release(gstate);
200
201         return SRD_ERR_PYTHON;
202 }
203
204 /**
205  * Get the value of a Python list item, returned as a newly
206  * allocated char *.
207  *
208  * @param[in] py_obj The list to probe.
209  * @param[in] idx Index of the list item to retrieve.
210  * @param[out] outstr Pointer to char * storage to be filled in.
211  *
212  * @return SRD_OK upon success, a (negative) error code otherwise.
213  *         The 'outstr' argument points to a g_malloc()ed string upon success.
214  *
215  * @private
216  */
217 SRD_PRIV int py_listitem_as_str(PyObject *py_obj, Py_ssize_t idx,
218                                 char **outstr)
219 {
220         PyGILState_STATE gstate;
221         ssize_t item_idx;
222         PyObject *py_value;
223
224         gstate = PyGILState_Ensure();
225
226         if (!PyList_Check(py_obj)) {
227                 srd_dbg("Object is not a list.");
228                 goto err;
229         }
230
231         item_idx = idx;
232         if (!(py_value = PyList_GetItem(py_obj, item_idx))) {
233                 srd_dbg("Couldn't get list item %zd.", item_idx);
234                 goto err;
235         }
236
237         PyGILState_Release(gstate);
238
239         return py_str_as_str(py_value, outstr);
240
241 err:
242         PyGILState_Release(gstate);
243
244         return SRD_ERR_PYTHON;
245 }
246
247 /**
248  * Get the value of a Python dictionary item, returned as a newly
249  * allocated char *.
250  *
251  * @param py_obj The dictionary to probe.
252  * @param py_key Key of the item to retrieve.
253  * @param outstr Pointer to char * storage to be filled in.
254  *
255  * @return SRD_OK upon success, a (negative) error code otherwise.
256  *         The 'outstr' argument points to a malloc()ed string upon success.
257  *
258  * @private
259  */
260 SRD_PRIV int py_pydictitem_as_str(PyObject *py_obj, PyObject *py_key,
261                                 char **outstr)
262 {
263         PyObject *py_value;
264         PyGILState_STATE gstate;
265
266         if (!py_obj || !py_key || !outstr)
267                 return SRD_ERR_ARG;
268
269         gstate = PyGILState_Ensure();
270
271         if (!PyDict_Check(py_obj)) {
272                 srd_dbg("Object is not a dictionary.");
273                 goto err;
274         }
275
276         if (!(py_value = PyDict_GetItem(py_obj, py_key))) {
277                 srd_dbg("Dictionary has no such key.");
278                 goto err;
279         }
280
281         if (!PyUnicode_Check(py_value)) {
282                 srd_dbg("Dictionary value should be a string.");
283                 goto err;
284         }
285
286         PyGILState_Release(gstate);
287
288         return py_str_as_str(py_value, outstr);
289
290 err:
291         PyGILState_Release(gstate);
292
293         return SRD_ERR_PYTHON;
294 }
295
296 /**
297  * Get the value of a Python dictionary item, returned as a newly
298  * allocated char *.
299  *
300  * @param py_obj The dictionary to probe.
301  * @param py_key Key of the item to retrieve.
302  * @param out TODO.
303  *
304  * @return SRD_OK upon success, a (negative) error code otherwise.
305  *
306  * @private
307  */
308 SRD_PRIV int py_pydictitem_as_long(PyObject *py_obj, PyObject *py_key, int64_t *out)
309 {
310         PyObject *py_value;
311         PyGILState_STATE gstate;
312
313         if (!py_obj || !py_key || !out)
314                 return SRD_ERR_ARG;
315
316         gstate = PyGILState_Ensure();
317
318         if (!PyDict_Check(py_obj)) {
319                 srd_dbg("Object is not a dictionary.");
320                 goto err;
321         }
322
323         if (!(py_value = PyDict_GetItem(py_obj, py_key))) {
324                 srd_dbg("Dictionary has no such key.");
325                 goto err;
326         }
327
328         if (!PyLong_Check(py_value)) {
329                 srd_dbg("Dictionary value should be a long.");
330                 goto err;
331         }
332
333         *out = PyLong_AsLongLong(py_value);
334
335         PyGILState_Release(gstate);
336
337         return SRD_OK;
338
339 err:
340         PyGILState_Release(gstate);
341
342         return SRD_ERR_PYTHON;
343 }
344
345 /**
346  * Get the value of a Python unicode string object, returned as a newly
347  * allocated char *.
348  *
349  * @param[in] py_str The unicode string object.
350  * @param[out] outstr ptr to char * storage to be filled in.
351  *
352  * @return SRD_OK upon success, a (negative) error code otherwise.
353  *         The 'outstr' argument points to a g_malloc()ed string upon success.
354  *
355  * @private
356  */
357 SRD_PRIV int py_str_as_str(PyObject *py_str, char **outstr)
358 {
359         PyObject *py_bytes;
360         char *str;
361         PyGILState_STATE gstate;
362
363         gstate = PyGILState_Ensure();
364
365         if (!PyUnicode_Check(py_str)) {
366                 srd_dbg("Object is not a string object.");
367                 PyGILState_Release(gstate);
368                 return SRD_ERR_PYTHON;
369         }
370
371         py_bytes = PyUnicode_AsUTF8String(py_str);
372         if (py_bytes) {
373                 str = g_strdup(PyBytes_AsString(py_bytes));
374                 Py_DECREF(py_bytes);
375                 if (str) {
376                         *outstr = str;
377                         PyGILState_Release(gstate);
378                         return SRD_OK;
379                 }
380         }
381         srd_exception_catch("Failed to extract string");
382
383         PyGILState_Release(gstate);
384
385         return SRD_ERR_PYTHON;
386 }
387
388 /**
389  * Convert a Python list of unicode strings to a C string vector.
390  * On success, a pointer to a newly allocated NUL-terminated array of
391  * allocated C strings is written to @a out_strv. The caller must g_free()
392  * each string and the array itself.
393  *
394  * @param[in] py_strseq The sequence object.
395  * @param[out] out_strv Address of string vector to be filled in.
396  *
397  * @return SRD_OK upon success, a (negative) error code otherwise.
398  *
399  * @private
400  */
401 SRD_PRIV int py_strseq_to_char(PyObject *py_strseq, char ***out_strv)
402 {
403         PyObject *py_item, *py_bytes;
404         char **strv, *str;
405         ssize_t seq_len, i;
406         PyGILState_STATE gstate;
407         int ret = SRD_ERR_PYTHON;
408
409         gstate = PyGILState_Ensure();
410
411         if (!PySequence_Check(py_strseq)) {
412                 srd_err("Object does not provide sequence protocol.");
413                 goto err;
414         }
415
416         seq_len = PySequence_Size(py_strseq);
417         if (seq_len < 0) {
418                 srd_exception_catch("Failed to obtain sequence size");
419                 goto err;
420         }
421
422         strv = g_try_new0(char *, seq_len + 1);
423         if (!strv) {
424                 srd_err("Failed to allocate result string vector.");
425                 ret = SRD_ERR_MALLOC;
426                 goto err;
427         }
428
429         for (i = 0; i < seq_len; i++) {
430                 py_item = PySequence_GetItem(py_strseq, i);
431                 if (!py_item)
432                         goto err_out;
433
434                 if (!PyUnicode_Check(py_item)) {
435                         Py_DECREF(py_item);
436                         goto err_out;
437                 }
438                 py_bytes = PyUnicode_AsUTF8String(py_item);
439                 Py_DECREF(py_item);
440                 if (!py_bytes)
441                         goto err_out;
442
443                 str = g_strdup(PyBytes_AsString(py_bytes));
444                 Py_DECREF(py_bytes);
445                 if (!str)
446                         goto err_out;
447
448                 strv[i] = str;
449         }
450         *out_strv = strv;
451
452         PyGILState_Release(gstate);
453
454         return SRD_OK;
455
456 err_out:
457         g_strfreev(strv);
458         srd_exception_catch("Failed to obtain string item");
459
460 err:
461         PyGILState_Release(gstate);
462
463         return ret;
464 }
465
466 /**
467  * Convert a Python scalar object to a GLib variant.
468  * Supported variant types are string, int64 and double.
469  *
470  * @param[in] py_obj The Python object. Must not be NULL.
471  * @return A floating reference to a new variant, or NULL on failure.
472  *
473  * @private
474  */
475 SRD_PRIV GVariant *py_obj_to_variant(PyObject *py_obj)
476 {
477         GVariant *var = NULL;
478         PyGILState_STATE gstate;
479
480         gstate = PyGILState_Ensure();
481
482         if (PyUnicode_Check(py_obj)) { /* string */
483                 PyObject *py_bytes;
484                 const char *str;
485
486                 py_bytes = PyUnicode_AsUTF8String(py_obj);
487                 if (py_bytes) {
488                         str = PyBytes_AsString(py_bytes);
489                         if (str)
490                                 var = g_variant_new_string(str);
491                         Py_DECREF(py_bytes);
492                 }
493                 if (!var)
494                         srd_exception_catch("Failed to extract string value");
495         } else if (PyLong_Check(py_obj)) { /* integer */
496                 int64_t val;
497
498                 val = PyLong_AsLongLong(py_obj);
499                 if (!PyErr_Occurred())
500                         var = g_variant_new_int64(val);
501                 else
502                         srd_exception_catch("Failed to extract integer value");
503         } else if (PyFloat_Check(py_obj)) { /* float */
504                 double val;
505
506                 val = PyFloat_AsDouble(py_obj);
507                 if (!PyErr_Occurred())
508                         var = g_variant_new_double(val);
509                 else
510                         srd_exception_catch("Failed to extract float value");
511         } else {
512                 srd_err("Failed to extract value of unsupported type.");
513         }
514
515         PyGILState_Release(gstate);
516
517         return var;
518 }