465f35015ce2bdb76daf108f496b9cec17e8d6d0
[babeltrace.git] / src / py-common / py-common.c
1 /*
2 * Copyright (c) 2019 EfficiOS Inc. and Linux Foundation
3 * Copyright (c) 2019 Philippe Proulx <pproulx@efficios.com>
4 * Copyright (c) 2019 Simon Marchi <simon.marchi@efficios.com>
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25 #define BT_LOG_OUTPUT_LEVEL log_level
26 #define BT_LOG_TAG "PY-COMMON"
27 #include "logging/log.h"
28
29 #include <Python.h>
30
31 #include "common/assert.h"
32 #include "py-common.h"
33
34 BT_HIDDEN
35 GString *bt_py_common_format_exception(PyObject *py_exc_type,
36 PyObject *py_exc_value, PyObject *py_exc_tb,
37 int log_level, bool chain)
38 {
39 PyObject *traceback_module = NULL;
40 PyObject *format_exception_func = NULL;
41 PyObject *exc_str_list = NULL;
42 GString *msg_buf = NULL;
43 const char *format_exc_func_name;
44 Py_ssize_t i;
45
46 /*
47 * Import the standard `traceback` module which contains the
48 * functions to format an exception.
49 */
50 traceback_module = PyImport_ImportModule("traceback");
51 if (!traceback_module) {
52 BT_LOGE_STR("Failed to import `traceback` module.");
53 goto error;
54 }
55
56 /*
57 * `py_exc_tb` can be `NULL`, when we fail to call a Python
58 * function from native code (there is no Python stack at that
59 * point). For example, a function which takes 5 positional
60 * arguments, but 8 were given.
61 */
62 format_exc_func_name = py_exc_tb ? "format_exception" :
63 "format_exception_only";
64 format_exception_func = PyObject_GetAttrString(traceback_module,
65 format_exc_func_name);
66 if (!format_exception_func) {
67 BT_LOGE("Cannot find `%s` attribute in `traceback` module.",
68 format_exc_func_name);
69 goto error;
70 }
71
72 if (!PyCallable_Check(format_exception_func)) {
73 BT_LOGE("`traceback.%s` attribute is not callable.",
74 format_exc_func_name);
75 goto error;
76 }
77
78 /*
79 * If we are calling format_exception_only, `py_exc_tb` is NULL, so the
80 * effective argument list is of length 2.
81 */
82 exc_str_list = PyObject_CallFunctionObjArgs(format_exception_func,
83 py_exc_type, py_exc_value, py_exc_tb, Py_None /* limit */,
84 chain ? Py_True : Py_False /* chain */, NULL);
85 if (!exc_str_list) {
86 if (BT_LOG_ON_ERROR) {
87 BT_LOGE("Failed to call `traceback.%s` function:",
88 format_exc_func_name);
89 PyErr_Print();
90 }
91
92 goto error;
93 }
94
95 msg_buf = g_string_new(NULL);
96
97 for (i = 0; i < PyList_Size(exc_str_list); i++) {
98 PyObject *exc_str;
99 const char *str;
100
101 exc_str = PyList_GetItem(exc_str_list, i);
102 BT_ASSERT(exc_str);
103
104 /* `str` is owned by `exc_str`, not by us */
105 str = PyUnicode_AsUTF8(exc_str);
106 if (!str) {
107 if (BT_LOG_ON_ERROR) {
108 BT_LOGE_STR("PyUnicode_AsUTF8() failed:");
109 PyErr_Print();
110 }
111
112 goto error;
113 }
114
115 /* `str` has a trailing newline */
116 g_string_append(msg_buf, str);
117 }
118
119 if (msg_buf->len > 0) {
120 /* Remove trailing newline if any */
121 if (msg_buf->str[msg_buf->len - 1] == '\n') {
122 g_string_truncate(msg_buf, msg_buf->len - 1);
123 }
124 }
125
126 goto end;
127
128 error:
129 if (msg_buf) {
130 g_string_free(msg_buf, TRUE);
131 msg_buf = NULL;
132 }
133
134 end:
135 Py_XDECREF(exc_str_list);
136 Py_XDECREF(format_exception_func);
137 Py_XDECREF(traceback_module);
138
139 return msg_buf;
140 }
141
142 BT_HIDDEN
143 GString *bt_py_common_format_current_exception(int log_level)
144 {
145 GString *result;
146 PyObject *py_exc_type = NULL;
147 PyObject *py_exc_value = NULL;
148 PyObject *py_exc_tb = NULL;
149
150 BT_ASSERT(PyErr_Occurred());
151 PyErr_Fetch(&py_exc_type, &py_exc_value, &py_exc_tb);
152 BT_ASSERT(py_exc_type);
153
154 /*
155 * Make sure `py_exc_value` is what we expected: an instance of
156 * `py_exc_type`.
157 */
158 PyErr_NormalizeException(&py_exc_type, &py_exc_value, &py_exc_tb);
159
160 result = bt_py_common_format_exception(py_exc_type, py_exc_value,
161 py_exc_tb, log_level, true);
162
163 /*
164 * We can safely call PyErr_Restore() because we always call
165 * PyErr_Fetch(), and having an error indicator is a function's
166 * precondition.
167 *
168 * PyErr_Restore() steals our references.
169 */
170 PyErr_Restore(py_exc_type, py_exc_value, py_exc_tb);
171
172 return result;
173 }
This page took 0.032044 seconds and 3 git commands to generate.