blob: 9f8c568b08ad2184e4d9170191417a72d4255771 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Traceback implementation */
3
Guido van Rossum65bf9f21997-04-29 18:33:38 +00004#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00007#include "frameobject.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#include "structmember.h"
Guido van Rossum7169dbb1992-02-26 15:17:59 +00009#include "osdefs.h"
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +000010#ifdef HAVE_FCNTL_H
11#include <fcntl.h>
12#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +000013
Nicholas Bastina7604bf2004-03-21 18:37:23 +000014#define OFF(x) offsetof(PyTracebackObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000015
Victor Stinner97f86b82015-04-01 18:38:01 +020016#define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
Victor Stinner54f939b2012-07-30 13:08:58 +020017#define MAX_STRING_LENGTH 500
Victor Stinner024e37a2011-03-31 01:31:06 +020018#define MAX_FRAME_DEPTH 100
19#define MAX_NTHREADS 100
20
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020021/* Function from Parser/tokenizer.c */
22extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +000023
Victor Stinnerbd303c12013-11-07 23:07:29 +010024_Py_IDENTIFIER(TextIOWrapper);
25_Py_IDENTIFIER(close);
26_Py_IDENTIFIER(open);
27_Py_IDENTIFIER(path);
28
Collin Winter3eed7652007-08-14 17:53:54 +000029static PyObject *
30tb_dir(PyTracebackObject *self)
31{
32 return Py_BuildValue("[ssss]", "tb_frame", "tb_next",
33 "tb_lasti", "tb_lineno");
34}
35
36static PyMethodDef tb_methods[] = {
37 {"__dir__", (PyCFunction)tb_dir, METH_NOARGS},
38 {NULL, NULL, 0, NULL},
39};
40
Neal Norwitz8dfc4a92007-08-11 06:39:53 +000041static PyMemberDef tb_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 {"tb_next", T_OBJECT, OFF(tb_next), READONLY},
43 {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY},
44 {"tb_lasti", T_INT, OFF(tb_lasti), READONLY},
45 {"tb_lineno", T_INT, OFF(tb_lineno), READONLY},
46 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000047};
48
Guido van Rossum3f5da241990-12-20 15:06:42 +000049static void
Nicholas Bastina7604bf2004-03-21 18:37:23 +000050tb_dealloc(PyTracebackObject *tb)
Guido van Rossum3f5da241990-12-20 15:06:42 +000051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 PyObject_GC_UnTrack(tb);
53 Py_TRASHCAN_SAFE_BEGIN(tb)
54 Py_XDECREF(tb->tb_next);
55 Py_XDECREF(tb->tb_frame);
56 PyObject_GC_Del(tb);
57 Py_TRASHCAN_SAFE_END(tb)
Guido van Rossum3f5da241990-12-20 15:06:42 +000058}
59
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000060static int
Nicholas Bastina7604bf2004-03-21 18:37:23 +000061tb_traverse(PyTracebackObject *tb, visitproc visit, void *arg)
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 Py_VISIT(tb->tb_next);
64 Py_VISIT(tb->tb_frame);
65 return 0;
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000066}
67
68static void
Nicholas Bastina7604bf2004-03-21 18:37:23 +000069tb_clear(PyTracebackObject *tb)
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 Py_CLEAR(tb->tb_next);
72 Py_CLEAR(tb->tb_frame);
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000073}
74
Tim Petersd7c36522001-10-22 19:34:09 +000075PyTypeObject PyTraceBack_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 PyVarObject_HEAD_INIT(&PyType_Type, 0)
77 "traceback",
78 sizeof(PyTracebackObject),
79 0,
80 (destructor)tb_dealloc, /*tp_dealloc*/
81 0, /*tp_print*/
82 0, /*tp_getattr*/
83 0, /*tp_setattr*/
84 0, /*tp_reserved*/
85 0, /*tp_repr*/
86 0, /*tp_as_number*/
87 0, /*tp_as_sequence*/
88 0, /*tp_as_mapping*/
89 0, /* tp_hash */
90 0, /* tp_call */
91 0, /* tp_str */
92 PyObject_GenericGetAttr, /* tp_getattro */
93 0, /* tp_setattro */
94 0, /* tp_as_buffer */
95 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
96 0, /* tp_doc */
97 (traverseproc)tb_traverse, /* tp_traverse */
98 (inquiry)tb_clear, /* tp_clear */
99 0, /* tp_richcompare */
100 0, /* tp_weaklistoffset */
101 0, /* tp_iter */
102 0, /* tp_iternext */
103 tb_methods, /* tp_methods */
104 tb_memberlist, /* tp_members */
105 0, /* tp_getset */
106 0, /* tp_base */
107 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000108};
109
Nicholas Bastina7604bf2004-03-21 18:37:23 +0000110static PyTracebackObject *
111newtracebackobject(PyTracebackObject *next, PyFrameObject *frame)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PyTracebackObject *tb;
114 if ((next != NULL && !PyTraceBack_Check(next)) ||
115 frame == NULL || !PyFrame_Check(frame)) {
116 PyErr_BadInternalCall();
117 return NULL;
118 }
119 tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type);
120 if (tb != NULL) {
121 Py_XINCREF(next);
122 tb->tb_next = next;
123 Py_XINCREF(frame);
124 tb->tb_frame = frame;
125 tb->tb_lasti = frame->f_lasti;
126 tb->tb_lineno = PyFrame_GetLineNumber(frame);
127 PyObject_GC_Track(tb);
128 }
129 return tb;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000130}
131
Guido van Rossum3f5da241990-12-20 15:06:42 +0000132int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000133PyTraceBack_Here(PyFrameObject *frame)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000134{
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300135 PyObject *exc, *val, *tb, *newtb;
136 PyErr_Fetch(&exc, &val, &tb);
137 newtb = (PyObject *)newtracebackobject((PyTracebackObject *)tb, frame);
138 if (newtb == NULL) {
139 _PyErr_ChainExceptions(exc, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 return -1;
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300141 }
142 PyErr_Restore(exc, val, newtb);
143 Py_XDECREF(tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 return 0;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000145}
146
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200147/* Insert a frame into the traceback for (funcname, filename, lineno). */
Serhiy Storchaka73c95f12015-06-21 15:59:46 +0300148void _PyTraceback_Add(const char *funcname, const char *filename, int lineno)
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200149{
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300150 PyObject *globals;
151 PyCodeObject *code;
152 PyFrameObject *frame;
153 PyObject *exc, *val, *tb;
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200154
155 /* Save and clear the current exception. Python functions must not be
156 called with an exception set. Calling Python functions happens when
157 the codec of the filesystem encoding is implemented in pure Python. */
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300158 PyErr_Fetch(&exc, &val, &tb);
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200159
160 globals = PyDict_New();
161 if (!globals)
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300162 goto error;
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200163 code = PyCode_NewEmpty(filename, funcname, lineno);
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300164 if (!code) {
165 Py_DECREF(globals);
166 goto error;
167 }
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200168 frame = PyFrame_New(PyThreadState_Get(), code, globals, NULL);
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300169 Py_DECREF(globals);
170 Py_DECREF(code);
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200171 if (!frame)
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300172 goto error;
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200173 frame->f_lineno = lineno;
174
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300175 PyErr_Restore(exc, val, tb);
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200176 PyTraceBack_Here(frame);
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300177 Py_DECREF(frame);
178 return;
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200179
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300180error:
181 _PyErr_ChainExceptions(exc, val, tb);
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200182}
183
Victor Stinner0fe25a42010-06-17 23:08:50 +0000184static PyObject *
185_Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io)
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000186{
Victor Stinner0fe25a42010-06-17 23:08:50 +0000187 Py_ssize_t i;
188 PyObject *binary;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 PyObject *v;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000190 Py_ssize_t npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 size_t taillen;
192 PyObject *syspath;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000193 PyObject *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 const char* tail;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000195 PyObject *filebytes;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000196 const char* filepath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 Py_ssize_t len;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000198 PyObject* result;
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000199
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000200 filebytes = PyUnicode_EncodeFSDefault(filename);
201 if (filebytes == NULL) {
Victor Stinner0fe25a42010-06-17 23:08:50 +0000202 PyErr_Clear();
203 return NULL;
204 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000205 filepath = PyBytes_AS_STRING(filebytes);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 /* Search tail of filename in sys.path before giving up */
Victor Stinner0fe25a42010-06-17 23:08:50 +0000208 tail = strrchr(filepath, SEP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (tail == NULL)
Victor Stinner0fe25a42010-06-17 23:08:50 +0000210 tail = filepath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 else
212 tail++;
213 taillen = strlen(tail);
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000214
Victor Stinnerbd303c12013-11-07 23:07:29 +0100215 syspath = _PySys_GetObjectId(&PyId_path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 if (syspath == NULL || !PyList_Check(syspath))
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000217 goto error;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000218 npath = PyList_Size(syspath);
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 for (i = 0; i < npath; i++) {
221 v = PyList_GetItem(syspath, i);
222 if (v == NULL) {
223 PyErr_Clear();
224 break;
225 }
226 if (!PyUnicode_Check(v))
227 continue;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000228 path = PyUnicode_EncodeFSDefault(v);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000229 if (path == NULL) {
230 PyErr_Clear();
231 continue;
232 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000233 len = PyBytes_GET_SIZE(path);
234 if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) {
235 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 continue; /* Too long */
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000237 }
238 strcpy(namebuf, PyBytes_AS_STRING(path));
239 Py_DECREF(path);
Victor Stinner98ea54c2014-08-15 23:30:40 +0200240 if (strlen(namebuf) != (size_t)len)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 continue; /* v contains '\0' */
242 if (len > 0 && namebuf[len-1] != SEP)
243 namebuf[len++] = SEP;
244 strcpy(namebuf+len, tail);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000245
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200246 binary = _PyObject_CallMethodId(io, &PyId_open, "ss", namebuf, "rb");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000247 if (binary != NULL) {
248 result = binary;
249 goto finally;
250 }
Victor Stinner0fe25a42010-06-17 23:08:50 +0000251 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000253 goto error;
254
255error:
256 result = NULL;
257finally:
258 Py_DECREF(filebytes);
259 return result;
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000260}
261
Christian Heimes33fe8092008-04-13 13:53:33 +0000262int
Victor Stinner0fe25a42010-06-17 23:08:50 +0000263_Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 int err = 0;
266 int fd;
267 int i;
268 char *found_encoding;
269 char *encoding;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000270 PyObject *io;
271 PyObject *binary;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PyObject *fob = NULL;
273 PyObject *lineobj = NULL;
Antoine Pitroub86680e2010-10-14 21:15:17 +0000274 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 char buf[MAXPATHLEN+1];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200276 int kind;
277 void *data;
Christian Heimes679db4a2008-01-18 09:56:22 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 /* open the file */
280 if (filename == NULL)
281 return 0;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000282
283 io = PyImport_ImportModuleNoBlock("io");
284 if (io == NULL)
285 return -1;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200286 binary = _PyObject_CallMethodId(io, &PyId_open, "Os", filename, "rb");
Victor Stinner0fe25a42010-06-17 23:08:50 +0000287
288 if (binary == NULL) {
Victor Stinnerceceaa02013-07-16 00:32:14 +0200289 PyErr_Clear();
290
Victor Stinner0fe25a42010-06-17 23:08:50 +0000291 binary = _Py_FindSourceFile(filename, buf, sizeof(buf), io);
292 if (binary == NULL) {
293 Py_DECREF(io);
Victor Stinnerceceaa02013-07-16 00:32:14 +0200294 return -1;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* use the right encoding to decode the file as unicode */
Victor Stinner0fe25a42010-06-17 23:08:50 +0000299 fd = PyObject_AsFileDescriptor(binary);
Christian Heimes8c077bc2013-07-21 01:53:10 +0200300 if (fd < 0) {
301 Py_DECREF(io);
302 Py_DECREF(binary);
Benjamin Peterson04b01dc2013-07-21 13:26:13 -0700303 return 0;
Christian Heimes8c077bc2013-07-21 01:53:10 +0200304 }
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200305 found_encoding = PyTokenizer_FindEncodingFilename(fd, filename);
Victor Stinner5272fa92013-12-19 13:39:32 +0100306 if (found_encoding == NULL)
307 PyErr_Clear();
Victor Stinner0fe25a42010-06-17 23:08:50 +0000308 encoding = (found_encoding != NULL) ? found_encoding : "utf-8";
Christian Heimes1f347292013-07-21 02:12:35 +0200309 /* Reset position */
310 if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
311 Py_DECREF(io);
312 Py_DECREF(binary);
313 PyMem_FREE(found_encoding);
Benjamin Peterson04b01dc2013-07-21 13:26:13 -0700314 return 0;
Christian Heimes1f347292013-07-21 02:12:35 +0200315 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200316 fob = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "Os", binary, encoding);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000317 Py_DECREF(io);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 PyMem_FREE(found_encoding);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (fob == NULL) {
321 PyErr_Clear();
Victor Stinner81f241a2015-03-25 02:25:25 +0100322
Victor Stinner3466bde2016-09-05 18:16:01 -0700323 res = _PyObject_CallMethodId(binary, &PyId_close, NULL);
Victor Stinner81f241a2015-03-25 02:25:25 +0100324 Py_DECREF(binary);
325 if (res)
326 Py_DECREF(res);
327 else
328 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 return 0;
330 }
Victor Stinner81f241a2015-03-25 02:25:25 +0100331 Py_DECREF(binary);
Christian Heimes33fe8092008-04-13 13:53:33 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 /* get the line number lineno */
334 for (i = 0; i < lineno; i++) {
335 Py_XDECREF(lineobj);
336 lineobj = PyFile_GetLine(fob, -1);
337 if (!lineobj) {
Victor Stinner5e78f4d2014-10-30 10:17:27 +0100338 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 err = -1;
340 break;
341 }
342 }
Victor Stinner3466bde2016-09-05 18:16:01 -0700343 res = _PyObject_CallMethodId(fob, &PyId_close, NULL);
Antoine Pitroub86680e2010-10-14 21:15:17 +0000344 if (res)
345 Py_DECREF(res);
346 else
347 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 Py_DECREF(fob);
349 if (!lineobj || !PyUnicode_Check(lineobj)) {
350 Py_XDECREF(lineobj);
351 return err;
352 }
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 /* remove the indentation of the line */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200355 kind = PyUnicode_KIND(lineobj);
356 data = PyUnicode_DATA(lineobj);
357 for (i=0; i < PyUnicode_GET_LENGTH(lineobj); i++) {
358 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
359 if (ch != ' ' && ch != '\t' && ch != '\014')
360 break;
361 }
362 if (i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 PyObject *truncated;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200364 truncated = PyUnicode_Substring(lineobj, i, PyUnicode_GET_LENGTH(lineobj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (truncated) {
366 Py_DECREF(lineobj);
367 lineobj = truncated;
368 } else {
369 PyErr_Clear();
370 }
371 }
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 /* Write some spaces before the line */
374 strcpy(buf, " ");
375 assert (strlen(buf) == 10);
376 while (indent > 0) {
Benjamin Peterson0f9b7d32013-07-21 13:29:37 -0700377 if (indent < 10)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 buf[indent] = '\0';
379 err = PyFile_WriteString(buf, f);
380 if (err != 0)
381 break;
382 indent -= 10;
383 }
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* finally display the line */
386 if (err == 0)
387 err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW);
388 Py_DECREF(lineobj);
389 if (err == 0)
390 err = PyFile_WriteString("\n", f);
391 return err;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000392}
393
Guido van Rossum7e8d26d1997-05-22 22:35:47 +0000394static int
Victor Stinner0fe25a42010-06-17 23:08:50 +0000395tb_displayline(PyObject *f, PyObject *filename, int lineno, PyObject *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396{
Victor Stinner0fe25a42010-06-17 23:08:50 +0000397 int err;
398 PyObject *line;
Christian Heimes33fe8092008-04-13 13:53:33 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 if (filename == NULL || name == NULL)
401 return -1;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000402 line = PyUnicode_FromFormat(" File \"%U\", line %d, in %U\n",
403 filename, lineno, name);
404 if (line == NULL)
405 return -1;
406 err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
407 Py_DECREF(line);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (err != 0)
409 return err;
Kristján Valur Jónssonc5963d32012-07-19 21:02:03 +0000410 /* ignore errors since we can't report them, can we? */
411 if (_Py_DisplaySourceLine(f, filename, lineno, 4))
412 PyErr_Clear();
413 return err;
Christian Heimes33fe8092008-04-13 13:53:33 +0000414}
415
416static int
417tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit)
418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 int err = 0;
420 long depth = 0;
Nick Coghland0034232016-08-15 13:11:34 +1000421 PyObject *last_file = NULL;
422 int last_line = -1;
423 PyObject *last_name = NULL;
424 long cnt = 0;
425 PyObject *line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 PyTracebackObject *tb1 = tb;
427 while (tb1 != NULL) {
428 depth++;
429 tb1 = tb1->tb_next;
430 }
431 while (tb != NULL && err == 0) {
432 if (depth <= limit) {
Nick Coghland0034232016-08-15 13:11:34 +1000433 if (last_file != NULL &&
434 tb->tb_frame->f_code->co_filename == last_file &&
435 last_line != -1 && tb->tb_lineno == last_line &&
436 last_name != NULL &&
437 tb->tb_frame->f_code->co_name == last_name) {
438 cnt++;
439 } else {
440 if (cnt > 3) {
441 line = PyUnicode_FromFormat(
442 " [Previous line repeated %d more times]\n", cnt-3);
443 err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
Victor Stinnera88b2f42016-08-20 03:05:13 +0200444 Py_DECREF(line);
Nick Coghland0034232016-08-15 13:11:34 +1000445 }
446 last_file = tb->tb_frame->f_code->co_filename;
447 last_line = tb->tb_lineno;
448 last_name = tb->tb_frame->f_code->co_name;
449 cnt = 0;
450 }
451 if (cnt < 3)
452 err = tb_displayline(f,
453 tb->tb_frame->f_code->co_filename,
454 tb->tb_lineno,
455 tb->tb_frame->f_code->co_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 }
457 depth--;
458 tb = tb->tb_next;
459 if (err == 0)
460 err = PyErr_CheckSignals();
461 }
Nick Coghland0034232016-08-15 13:11:34 +1000462 if (cnt > 3) {
463 line = PyUnicode_FromFormat(
464 " [Previous line repeated %d more times]\n", cnt-3);
465 err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
Victor Stinnera88b2f42016-08-20 03:05:13 +0200466 Py_DECREF(line);
Nick Coghland0034232016-08-15 13:11:34 +1000467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return err;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000469}
470
Christian Heimes0fbab7f2007-12-04 21:55:18 +0000471#define PyTraceBack_LIMIT 1000
472
Guido van Rossum3f5da241990-12-20 15:06:42 +0000473int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000474PyTraceBack_Print(PyObject *v, PyObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 int err;
477 PyObject *limitv;
478 long limit = PyTraceBack_LIMIT;
Christian Heimes0fbab7f2007-12-04 21:55:18 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (v == NULL)
481 return 0;
482 if (!PyTraceBack_Check(v)) {
483 PyErr_BadInternalCall();
484 return -1;
485 }
486 limitv = PySys_GetObject("tracebacklimit");
487 if (limitv) {
488 PyObject *exc_type, *exc_value, *exc_tb;
Christian Heimes0fbab7f2007-12-04 21:55:18 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
491 limit = PyLong_AsLong(limitv);
492 if (limit == -1 && PyErr_Occurred()) {
493 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
494 limit = PyTraceBack_LIMIT;
495 }
496 else {
497 Py_XDECREF(exc_type);
498 Py_XDECREF(exc_value);
499 Py_XDECREF(exc_tb);
500 return 0;
501 }
502 }
503 else if (limit <= 0) {
504 limit = PyTraceBack_LIMIT;
505 }
506 PyErr_Restore(exc_type, exc_value, exc_tb);
507 }
508 err = PyFile_WriteString("Traceback (most recent call last):\n", f);
509 if (!err)
510 err = tb_printinternal((PyTracebackObject *)v, f, limit);
511 return err;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000512}
Victor Stinner024e37a2011-03-31 01:31:06 +0200513
514/* Reverse a string. For example, "abcd" becomes "dcba".
515
516 This function is signal safe. */
517
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100518void
519_Py_DumpDecimal(int fd, unsigned long value)
Victor Stinner024e37a2011-03-31 01:31:06 +0200520{
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100521 /* maximum number of characters required for output of %lld or %p.
522 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
523 plus 1 for the null byte. 53/22 is an upper bound for log10(256). */
524 char buffer[1 + (sizeof(unsigned long)*53-1) / 22 + 1];
525 char *ptr, *end;
Victor Stinner024e37a2011-03-31 01:31:06 +0200526
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100527 end = &buffer[Py_ARRAY_LENGTH(buffer) - 1];
528 ptr = end;
529 *ptr = '\0';
Victor Stinner024e37a2011-03-31 01:31:06 +0200530 do {
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100531 --ptr;
532 assert(ptr >= buffer);
533 *ptr = '0' + (value % 10);
Victor Stinner024e37a2011-03-31 01:31:06 +0200534 value /= 10;
Victor Stinner024e37a2011-03-31 01:31:06 +0200535 } while (value);
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100536
537 _Py_write_noraise(fd, ptr, end - ptr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200538}
539
Guido van Rossum7be5d7d2013-10-20 18:21:02 -0700540/* Format an integer in range [0; 0xffffffff] to hexadecimal of 'width' digits,
Victor Stinner024e37a2011-03-31 01:31:06 +0200541 and write it into the file fd.
542
543 This function is signal safe. */
544
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100545void
546_Py_DumpHexadecimal(int fd, unsigned long value, Py_ssize_t width)
Victor Stinner024e37a2011-03-31 01:31:06 +0200547{
Victor Stinner013024e2016-03-16 09:43:14 +0100548 char buffer[sizeof(unsigned long) * 2 + 1], *ptr, *end;
549 const Py_ssize_t size = Py_ARRAY_LENGTH(buffer) - 1;
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100550
551 if (width > size)
552 width = size;
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100553 /* it's ok if width is negative */
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100554
Victor Stinner013024e2016-03-16 09:43:14 +0100555 end = &buffer[size];
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100556 ptr = end;
557 *ptr = '\0';
Victor Stinner024e37a2011-03-31 01:31:06 +0200558 do {
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100559 --ptr;
560 assert(ptr >= buffer);
561 *ptr = Py_hexdigits[value & 15];
Victor Stinner024e37a2011-03-31 01:31:06 +0200562 value >>= 4;
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100563 } while ((end - ptr) < width || value);
564
565 _Py_write_noraise(fd, ptr, end - ptr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200566}
567
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100568void
569_Py_DumpASCII(int fd, PyObject *text)
Victor Stinner024e37a2011-03-31 01:31:06 +0200570{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200571 PyASCIIObject *ascii = (PyASCIIObject *)text;
Victor Stinner024e37a2011-03-31 01:31:06 +0200572 Py_ssize_t i, size;
573 int truncated;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200574 int kind;
Victor Stinnera336de72011-10-05 22:44:12 +0200575 void *data = NULL;
576 wchar_t *wstr = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200577 Py_UCS4 ch;
Victor Stinner024e37a2011-03-31 01:31:06 +0200578
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100579 if (!PyUnicode_Check(text))
580 return;
581
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200582 size = ascii->length;
583 kind = ascii->state.kind;
Victor Stinner1c3069a2016-03-23 16:10:07 +0100584 if (kind == PyUnicode_WCHAR_KIND) {
585 wstr = ((PyASCIIObject *)text)->wstr;
586 if (wstr == NULL)
587 return;
588 size = ((PyCompactUnicodeObject *)text)->wstr_length;
589 }
590 else if (ascii->state.compact) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200591 if (ascii->state.ascii)
592 data = ((PyASCIIObject*)text) + 1;
593 else
594 data = ((PyCompactUnicodeObject*)text) + 1;
595 }
Victor Stinner1c3069a2016-03-23 16:10:07 +0100596 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200597 data = ((PyUnicodeObject *)text)->data.any;
598 if (data == NULL)
599 return;
600 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200601
602 if (MAX_STRING_LENGTH < size) {
603 size = MAX_STRING_LENGTH;
604 truncated = 1;
605 }
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100606 else {
Victor Stinner024e37a2011-03-31 01:31:06 +0200607 truncated = 0;
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100608 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200609
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200610 for (i=0; i < size; i++) {
Victor Stinnera336de72011-10-05 22:44:12 +0200611 if (kind != PyUnicode_WCHAR_KIND)
612 ch = PyUnicode_READ(kind, data, i);
613 else
614 ch = wstr[i];
Victor Stinnerb86f08f2014-10-03 14:18:09 +0200615 if (' ' <= ch && ch <= 126) {
616 /* printable ASCII character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200617 char c = (char)ch;
Victor Stinner97f86b82015-04-01 18:38:01 +0200618 _Py_write_noraise(fd, &c, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200619 }
Victor Stinnerb86f08f2014-10-03 14:18:09 +0200620 else if (ch <= 0xff) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200621 PUTS(fd, "\\x");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100622 _Py_DumpHexadecimal(fd, ch, 2);
Victor Stinner024e37a2011-03-31 01:31:06 +0200623 }
Victor Stinnerb86f08f2014-10-03 14:18:09 +0200624 else if (ch <= 0xffff) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200625 PUTS(fd, "\\u");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100626 _Py_DumpHexadecimal(fd, ch, 4);
Victor Stinner024e37a2011-03-31 01:31:06 +0200627 }
628 else {
629 PUTS(fd, "\\U");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100630 _Py_DumpHexadecimal(fd, ch, 8);
Victor Stinner024e37a2011-03-31 01:31:06 +0200631 }
632 }
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100633 if (truncated) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200634 PUTS(fd, "...");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100635 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200636}
637
638/* Write a frame into the file fd: "File "xxx", line xxx in xxx".
639
640 This function is signal safe. */
641
642static void
643dump_frame(int fd, PyFrameObject *frame)
644{
645 PyCodeObject *code;
646 int lineno;
647
648 code = frame->f_code;
649 PUTS(fd, " File ");
650 if (code != NULL && code->co_filename != NULL
651 && PyUnicode_Check(code->co_filename))
652 {
Victor Stinner97f86b82015-04-01 18:38:01 +0200653 PUTS(fd, "\"");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100654 _Py_DumpASCII(fd, code->co_filename);
Victor Stinner97f86b82015-04-01 18:38:01 +0200655 PUTS(fd, "\"");
Victor Stinner024e37a2011-03-31 01:31:06 +0200656 } else {
657 PUTS(fd, "???");
658 }
659
660 /* PyFrame_GetLineNumber() was introduced in Python 2.7.0 and 3.2.0 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200661 lineno = PyCode_Addr2Line(code, frame->f_lasti);
Victor Stinner024e37a2011-03-31 01:31:06 +0200662 PUTS(fd, ", line ");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100663 if (lineno >= 0) {
664 _Py_DumpDecimal(fd, (unsigned long)lineno);
665 }
666 else {
667 PUTS(fd, "???");
668 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200669 PUTS(fd, " in ");
670
671 if (code != NULL && code->co_name != NULL
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100672 && PyUnicode_Check(code->co_name)) {
673 _Py_DumpASCII(fd, code->co_name);
674 }
675 else {
Victor Stinner024e37a2011-03-31 01:31:06 +0200676 PUTS(fd, "???");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100677 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200678
Victor Stinner97f86b82015-04-01 18:38:01 +0200679 PUTS(fd, "\n");
Victor Stinner024e37a2011-03-31 01:31:06 +0200680}
681
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200682static void
Victor Stinner024e37a2011-03-31 01:31:06 +0200683dump_traceback(int fd, PyThreadState *tstate, int write_header)
684{
685 PyFrameObject *frame;
686 unsigned int depth;
687
Victor Stinner024e37a2011-03-31 01:31:06 +0200688 if (write_header)
Guido van Rossum7be5d7d2013-10-20 18:21:02 -0700689 PUTS(fd, "Stack (most recent call first):\n");
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200690
691 frame = _PyThreadState_GetFrame(tstate);
692 if (frame == NULL)
693 return;
694
Victor Stinner024e37a2011-03-31 01:31:06 +0200695 depth = 0;
696 while (frame != NULL) {
697 if (MAX_FRAME_DEPTH <= depth) {
698 PUTS(fd, " ...\n");
699 break;
700 }
701 if (!PyFrame_Check(frame))
702 break;
703 dump_frame(fd, frame);
704 frame = frame->f_back;
705 depth++;
706 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200707}
708
Victor Stinner97f86b82015-04-01 18:38:01 +0200709/* Dump the traceback of a Python thread into fd. Use write() to write the
710 traceback and retry if write() is interrupted by a signal (failed with
711 EINTR), but don't call the Python signal handler.
712
713 The caller is responsible to call PyErr_CheckSignals() to call Python signal
714 handlers if signals were received. */
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200715void
Victor Stinner024e37a2011-03-31 01:31:06 +0200716_Py_DumpTraceback(int fd, PyThreadState *tstate)
717{
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200718 dump_traceback(fd, tstate, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200719}
720
721/* Write the thread identifier into the file 'fd': "Current thread 0xHHHH:\" if
722 is_current is true, "Thread 0xHHHH:\n" otherwise.
723
724 This function is signal safe. */
725
726static void
727write_thread_id(int fd, PyThreadState *tstate, int is_current)
728{
729 if (is_current)
730 PUTS(fd, "Current thread 0x");
731 else
732 PUTS(fd, "Thread 0x");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100733 _Py_DumpHexadecimal(fd,
734 (unsigned long)tstate->thread_id,
735 sizeof(unsigned long) * 2);
Guido van Rossum7be5d7d2013-10-20 18:21:02 -0700736 PUTS(fd, " (most recent call first):\n");
Victor Stinner024e37a2011-03-31 01:31:06 +0200737}
738
Victor Stinner97f86b82015-04-01 18:38:01 +0200739/* Dump the traceback of all Python threads into fd. Use write() to write the
740 traceback and retry if write() is interrupted by a signal (failed with
741 EINTR), but don't call the Python signal handler.
742
743 The caller is responsible to call PyErr_CheckSignals() to call Python signal
744 handlers if signals were received. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200745const char*
746_Py_DumpTracebackThreads(int fd, PyInterpreterState *interp,
Victor Stinner861d9ab2016-03-16 22:45:24 +0100747 PyThreadState *current_tstate)
Victor Stinner024e37a2011-03-31 01:31:06 +0200748{
749 PyThreadState *tstate;
750 unsigned int nthreads;
751
Victor Stinner861d9ab2016-03-16 22:45:24 +0100752#ifdef WITH_THREAD
753 if (current_tstate == NULL) {
754 /* _Py_DumpTracebackThreads() is called from signal handlers by
755 faulthandler.
756
757 SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals
758 and are thus delivered to the thread that caused the fault. Get the
759 Python thread state of the current thread.
760
761 PyThreadState_Get() doesn't give the state of the thread that caused
762 the fault if the thread released the GIL, and so this function
763 cannot be used. Read the thread local storage (TLS) instead: call
764 PyGILState_GetThisThreadState(). */
765 current_tstate = PyGILState_GetThisThreadState();
766 }
767
768 if (interp == NULL) {
769 if (current_tstate == NULL) {
770 interp = _PyGILState_GetInterpreterStateUnsafe();
771 if (interp == NULL) {
772 /* We need the interpreter state to get Python threads */
773 return "unable to get the interpreter state";
774 }
775 }
776 else {
777 interp = current_tstate->interp;
778 }
779 }
780#else
781 if (current_tstate == NULL) {
782 /* Call _PyThreadState_UncheckedGet() instead of PyThreadState_Get()
783 to not fail with a fatal error if the thread state is NULL. */
Berker Peksag531396c2016-06-17 13:25:01 +0300784 current_tstate = _PyThreadState_UncheckedGet();
Victor Stinner861d9ab2016-03-16 22:45:24 +0100785 }
786
787 if (interp == NULL) {
788 if (current_tstate == NULL) {
789 /* We need the interpreter state to get Python threads */
790 return "unable to get the interpreter state";
791 }
792 interp = current_tstate->interp;
793 }
794#endif
795 assert(interp != NULL);
796
Victor Stinner024e37a2011-03-31 01:31:06 +0200797 /* Get the current interpreter from the current thread */
798 tstate = PyInterpreterState_ThreadHead(interp);
799 if (tstate == NULL)
800 return "unable to get the thread head state";
801
802 /* Dump the traceback of each thread */
803 tstate = PyInterpreterState_ThreadHead(interp);
804 nthreads = 0;
Steve Dower8fc89802015-04-12 00:26:27 -0400805 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner024e37a2011-03-31 01:31:06 +0200806 do
807 {
808 if (nthreads != 0)
Victor Stinner97f86b82015-04-01 18:38:01 +0200809 PUTS(fd, "\n");
Victor Stinner024e37a2011-03-31 01:31:06 +0200810 if (nthreads >= MAX_NTHREADS) {
811 PUTS(fd, "...\n");
812 break;
813 }
Victor Stinner861d9ab2016-03-16 22:45:24 +0100814 write_thread_id(fd, tstate, tstate == current_tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +0200815 dump_traceback(fd, tstate, 0);
816 tstate = PyThreadState_Next(tstate);
817 nthreads++;
818 } while (tstate != NULL);
Steve Dower8fc89802015-04-12 00:26:27 -0400819 _Py_END_SUPPRESS_IPH
Victor Stinner024e37a2011-03-31 01:31:06 +0200820
821 return NULL;
822}
823