2 * This file is part of the sigrok project.
4 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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 3 of the License, or
9 * (at your option) any later version.
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.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include "sigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
21 #include "sigrokdecode-internal.h"
25 #include <frameobject.h> /* Python header not pulled in by default. */
27 SRD_PRIV void srd_exception_catch(const char *format, ...)
29 PyObject *etype, *evalue, *etb, *py_str;
30 PyTracebackObject *py_tb;
33 char *ename, *str, *tracestr;
35 if (!PyErr_Occurred())
36 /* Nothing is wrong. */
39 PyErr_Fetch(&etype, &evalue, &etb);
40 PyErr_NormalizeException(&etype, &evalue, &etb);
42 if (!(py_str = PyObject_Str(evalue))) {
43 /* Shouldn't happen. */
44 srd_dbg("Failed to convert exception value to string.");
48 msg = g_string_sized_new(128);
49 va_start(args, format);
50 g_string_vprintf(msg, format, args);
55 ename = (char *)Py_TYPE(evalue)->tp_name;
57 ename = "(unknown exception)";
59 /* Send the exception error message(s) to srd_err(). */
60 py_str_as_str(py_str, &str);
61 g_string_append(msg, ename);
62 g_string_append(msg, ": ");
63 g_string_append(msg, str);
67 /* Send a more precise error location to srd_dbg(), if we have it. */
68 if (etb && etb != Py_None) {
70 py_tb = (PyTracebackObject *)etb;
71 py_str = PyUnicode_FromFormat("%U:%d in %U",
72 py_tb->tb_frame->f_code->co_filename,
73 py_tb->tb_frame->f_lineno,
74 py_tb->tb_frame->f_code->co_name);
75 py_str_as_str(py_str, &tracestr);
77 g_string_printf(msg, "%s in %s: %s", ename, tracestr, str);
82 g_string_free(msg, TRUE);