blob: ba979aad8fa9e1bcadade46e727e8743b4aa51f8 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06005#include "internal/pystate.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00006
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#include "frameobject.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include "structmember.h"
Guido van Rossum7169dbb1992-02-26 15:17:59 +000010#include "osdefs.h"
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +000011#ifdef HAVE_FCNTL_H
12#include <fcntl.h>
13#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +000014
Nicholas Bastina7604bf2004-03-21 18:37:23 +000015#define OFF(x) offsetof(PyTracebackObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +000016
Victor Stinner97f86b82015-04-01 18:38:01 +020017#define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
Victor Stinner54f939b2012-07-30 13:08:58 +020018#define MAX_STRING_LENGTH 500
Victor Stinner024e37a2011-03-31 01:31:06 +020019#define MAX_FRAME_DEPTH 100
20#define MAX_NTHREADS 100
21
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020022/* Function from Parser/tokenizer.c */
23extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +000024
Victor Stinnerbd303c12013-11-07 23:07:29 +010025_Py_IDENTIFIER(TextIOWrapper);
26_Py_IDENTIFIER(close);
27_Py_IDENTIFIER(open);
28_Py_IDENTIFIER(path);
29
Collin Winter3eed7652007-08-14 17:53:54 +000030static PyObject *
31tb_dir(PyTracebackObject *self)
32{
33 return Py_BuildValue("[ssss]", "tb_frame", "tb_next",
34 "tb_lasti", "tb_lineno");
35}
36
37static PyMethodDef tb_methods[] = {
38 {"__dir__", (PyCFunction)tb_dir, METH_NOARGS},
39 {NULL, NULL, 0, NULL},
40};
41
Neal Norwitz8dfc4a92007-08-11 06:39:53 +000042static PyMemberDef tb_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 {"tb_next", T_OBJECT, OFF(tb_next), READONLY},
44 {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY},
45 {"tb_lasti", T_INT, OFF(tb_lasti), READONLY},
46 {"tb_lineno", T_INT, OFF(tb_lineno), READONLY},
47 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +000048};
49
Guido van Rossum3f5da241990-12-20 15:06:42 +000050static void
Nicholas Bastina7604bf2004-03-21 18:37:23 +000051tb_dealloc(PyTracebackObject *tb)
Guido van Rossum3f5da241990-12-20 15:06:42 +000052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 PyObject_GC_UnTrack(tb);
54 Py_TRASHCAN_SAFE_BEGIN(tb)
55 Py_XDECREF(tb->tb_next);
56 Py_XDECREF(tb->tb_frame);
57 PyObject_GC_Del(tb);
58 Py_TRASHCAN_SAFE_END(tb)
Guido van Rossum3f5da241990-12-20 15:06:42 +000059}
60
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000061static int
Nicholas Bastina7604bf2004-03-21 18:37:23 +000062tb_traverse(PyTracebackObject *tb, visitproc visit, void *arg)
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 Py_VISIT(tb->tb_next);
65 Py_VISIT(tb->tb_frame);
66 return 0;
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000067}
68
69static void
Nicholas Bastina7604bf2004-03-21 18:37:23 +000070tb_clear(PyTracebackObject *tb)
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 Py_CLEAR(tb->tb_next);
73 Py_CLEAR(tb->tb_frame);
Jeremy Hyltonfd14d8e2001-10-22 22:17:41 +000074}
75
Tim Petersd7c36522001-10-22 19:34:09 +000076PyTypeObject PyTraceBack_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 PyVarObject_HEAD_INIT(&PyType_Type, 0)
78 "traceback",
79 sizeof(PyTracebackObject),
80 0,
81 (destructor)tb_dealloc, /*tp_dealloc*/
82 0, /*tp_print*/
83 0, /*tp_getattr*/
84 0, /*tp_setattr*/
85 0, /*tp_reserved*/
86 0, /*tp_repr*/
87 0, /*tp_as_number*/
88 0, /*tp_as_sequence*/
89 0, /*tp_as_mapping*/
90 0, /* tp_hash */
91 0, /* tp_call */
92 0, /* tp_str */
93 PyObject_GenericGetAttr, /* tp_getattro */
94 0, /* tp_setattro */
95 0, /* tp_as_buffer */
96 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
97 0, /* tp_doc */
98 (traverseproc)tb_traverse, /* tp_traverse */
99 (inquiry)tb_clear, /* tp_clear */
100 0, /* tp_richcompare */
101 0, /* tp_weaklistoffset */
102 0, /* tp_iter */
103 0, /* tp_iternext */
104 tb_methods, /* tp_methods */
105 tb_memberlist, /* tp_members */
106 0, /* tp_getset */
107 0, /* tp_base */
108 0, /* tp_dict */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000109};
110
Nicholas Bastina7604bf2004-03-21 18:37:23 +0000111static PyTracebackObject *
112newtracebackobject(PyTracebackObject *next, PyFrameObject *frame)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 PyTracebackObject *tb;
115 if ((next != NULL && !PyTraceBack_Check(next)) ||
116 frame == NULL || !PyFrame_Check(frame)) {
117 PyErr_BadInternalCall();
118 return NULL;
119 }
120 tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type);
121 if (tb != NULL) {
122 Py_XINCREF(next);
123 tb->tb_next = next;
124 Py_XINCREF(frame);
125 tb->tb_frame = frame;
126 tb->tb_lasti = frame->f_lasti;
127 tb->tb_lineno = PyFrame_GetLineNumber(frame);
128 PyObject_GC_Track(tb);
129 }
130 return tb;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000131}
132
Guido van Rossum3f5da241990-12-20 15:06:42 +0000133int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000134PyTraceBack_Here(PyFrameObject *frame)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000135{
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300136 PyObject *exc, *val, *tb, *newtb;
137 PyErr_Fetch(&exc, &val, &tb);
138 newtb = (PyObject *)newtracebackobject((PyTracebackObject *)tb, frame);
139 if (newtb == NULL) {
140 _PyErr_ChainExceptions(exc, val, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 return -1;
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300142 }
143 PyErr_Restore(exc, val, newtb);
144 Py_XDECREF(tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 return 0;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000146}
147
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200148/* Insert a frame into the traceback for (funcname, filename, lineno). */
Serhiy Storchaka73c95f12015-06-21 15:59:46 +0300149void _PyTraceback_Add(const char *funcname, const char *filename, int lineno)
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200150{
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300151 PyObject *globals;
152 PyCodeObject *code;
153 PyFrameObject *frame;
154 PyObject *exc, *val, *tb;
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200155
156 /* Save and clear the current exception. Python functions must not be
157 called with an exception set. Calling Python functions happens when
158 the codec of the filesystem encoding is implemented in pure Python. */
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300159 PyErr_Fetch(&exc, &val, &tb);
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200160
161 globals = PyDict_New();
162 if (!globals)
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300163 goto error;
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200164 code = PyCode_NewEmpty(filename, funcname, lineno);
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300165 if (!code) {
166 Py_DECREF(globals);
167 goto error;
168 }
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200169 frame = PyFrame_New(PyThreadState_Get(), code, globals, NULL);
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300170 Py_DECREF(globals);
171 Py_DECREF(code);
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200172 if (!frame)
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300173 goto error;
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200174 frame->f_lineno = lineno;
175
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300176 PyErr_Restore(exc, val, tb);
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200177 PyTraceBack_Here(frame);
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300178 Py_DECREF(frame);
179 return;
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200180
Serhiy Storchaka04eb7772016-10-18 13:23:18 +0300181error:
182 _PyErr_ChainExceptions(exc, val, tb);
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200183}
184
Victor Stinner0fe25a42010-06-17 23:08:50 +0000185static PyObject *
186_Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io)
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000187{
Victor Stinner0fe25a42010-06-17 23:08:50 +0000188 Py_ssize_t i;
189 PyObject *binary;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 PyObject *v;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000191 Py_ssize_t npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 size_t taillen;
193 PyObject *syspath;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000194 PyObject *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 const char* tail;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000196 PyObject *filebytes;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000197 const char* filepath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 Py_ssize_t len;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000199 PyObject* result;
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000200
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000201 filebytes = PyUnicode_EncodeFSDefault(filename);
202 if (filebytes == NULL) {
Victor Stinner0fe25a42010-06-17 23:08:50 +0000203 PyErr_Clear();
204 return NULL;
205 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000206 filepath = PyBytes_AS_STRING(filebytes);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* Search tail of filename in sys.path before giving up */
Victor Stinner0fe25a42010-06-17 23:08:50 +0000209 tail = strrchr(filepath, SEP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (tail == NULL)
Victor Stinner0fe25a42010-06-17 23:08:50 +0000211 tail = filepath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 else
213 tail++;
214 taillen = strlen(tail);
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000215
Victor Stinnerbd303c12013-11-07 23:07:29 +0100216 syspath = _PySys_GetObjectId(&PyId_path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (syspath == NULL || !PyList_Check(syspath))
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000218 goto error;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000219 npath = PyList_Size(syspath);
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 for (i = 0; i < npath; i++) {
222 v = PyList_GetItem(syspath, i);
223 if (v == NULL) {
224 PyErr_Clear();
225 break;
226 }
227 if (!PyUnicode_Check(v))
228 continue;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000229 path = PyUnicode_EncodeFSDefault(v);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000230 if (path == NULL) {
231 PyErr_Clear();
232 continue;
233 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000234 len = PyBytes_GET_SIZE(path);
235 if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) {
236 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 continue; /* Too long */
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000238 }
239 strcpy(namebuf, PyBytes_AS_STRING(path));
240 Py_DECREF(path);
Victor Stinner98ea54c2014-08-15 23:30:40 +0200241 if (strlen(namebuf) != (size_t)len)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 continue; /* v contains '\0' */
243 if (len > 0 && namebuf[len-1] != SEP)
244 namebuf[len++] = SEP;
245 strcpy(namebuf+len, tail);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000246
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200247 binary = _PyObject_CallMethodId(io, &PyId_open, "ss", namebuf, "rb");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000248 if (binary != NULL) {
249 result = binary;
250 goto finally;
251 }
Victor Stinner0fe25a42010-06-17 23:08:50 +0000252 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000254 goto error;
255
256error:
257 result = NULL;
258finally:
259 Py_DECREF(filebytes);
260 return result;
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000261}
262
Christian Heimes33fe8092008-04-13 13:53:33 +0000263int
Victor Stinner0fe25a42010-06-17 23:08:50 +0000264_Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 int err = 0;
267 int fd;
268 int i;
269 char *found_encoding;
270 char *encoding;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000271 PyObject *io;
272 PyObject *binary;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 PyObject *fob = NULL;
274 PyObject *lineobj = NULL;
Antoine Pitroub86680e2010-10-14 21:15:17 +0000275 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 char buf[MAXPATHLEN+1];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200277 int kind;
278 void *data;
Christian Heimes679db4a2008-01-18 09:56:22 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 /* open the file */
281 if (filename == NULL)
282 return 0;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000283
284 io = PyImport_ImportModuleNoBlock("io");
285 if (io == NULL)
286 return -1;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200287 binary = _PyObject_CallMethodId(io, &PyId_open, "Os", filename, "rb");
Victor Stinner0fe25a42010-06-17 23:08:50 +0000288
289 if (binary == NULL) {
Victor Stinnerceceaa02013-07-16 00:32:14 +0200290 PyErr_Clear();
291
Victor Stinner0fe25a42010-06-17 23:08:50 +0000292 binary = _Py_FindSourceFile(filename, buf, sizeof(buf), io);
293 if (binary == NULL) {
294 Py_DECREF(io);
Victor Stinnerceceaa02013-07-16 00:32:14 +0200295 return -1;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000296 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 /* use the right encoding to decode the file as unicode */
Victor Stinner0fe25a42010-06-17 23:08:50 +0000300 fd = PyObject_AsFileDescriptor(binary);
Christian Heimes8c077bc2013-07-21 01:53:10 +0200301 if (fd < 0) {
302 Py_DECREF(io);
303 Py_DECREF(binary);
Benjamin Peterson04b01dc2013-07-21 13:26:13 -0700304 return 0;
Christian Heimes8c077bc2013-07-21 01:53:10 +0200305 }
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200306 found_encoding = PyTokenizer_FindEncodingFilename(fd, filename);
Victor Stinner5272fa92013-12-19 13:39:32 +0100307 if (found_encoding == NULL)
308 PyErr_Clear();
Victor Stinner0fe25a42010-06-17 23:08:50 +0000309 encoding = (found_encoding != NULL) ? found_encoding : "utf-8";
Christian Heimes1f347292013-07-21 02:12:35 +0200310 /* Reset position */
311 if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
312 Py_DECREF(io);
313 Py_DECREF(binary);
314 PyMem_FREE(found_encoding);
Benjamin Peterson04b01dc2013-07-21 13:26:13 -0700315 return 0;
Christian Heimes1f347292013-07-21 02:12:35 +0200316 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200317 fob = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "Os", binary, encoding);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000318 Py_DECREF(io);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 PyMem_FREE(found_encoding);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (fob == NULL) {
322 PyErr_Clear();
Victor Stinner81f241a2015-03-25 02:25:25 +0100323
Victor Stinner3466bde2016-09-05 18:16:01 -0700324 res = _PyObject_CallMethodId(binary, &PyId_close, NULL);
Victor Stinner81f241a2015-03-25 02:25:25 +0100325 Py_DECREF(binary);
326 if (res)
327 Py_DECREF(res);
328 else
329 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return 0;
331 }
Victor Stinner81f241a2015-03-25 02:25:25 +0100332 Py_DECREF(binary);
Christian Heimes33fe8092008-04-13 13:53:33 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 /* get the line number lineno */
335 for (i = 0; i < lineno; i++) {
336 Py_XDECREF(lineobj);
337 lineobj = PyFile_GetLine(fob, -1);
338 if (!lineobj) {
Victor Stinner5e78f4d2014-10-30 10:17:27 +0100339 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 err = -1;
341 break;
342 }
343 }
Victor Stinner3466bde2016-09-05 18:16:01 -0700344 res = _PyObject_CallMethodId(fob, &PyId_close, NULL);
Antoine Pitroub86680e2010-10-14 21:15:17 +0000345 if (res)
346 Py_DECREF(res);
347 else
348 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 Py_DECREF(fob);
350 if (!lineobj || !PyUnicode_Check(lineobj)) {
351 Py_XDECREF(lineobj);
352 return err;
353 }
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 /* remove the indentation of the line */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200356 kind = PyUnicode_KIND(lineobj);
357 data = PyUnicode_DATA(lineobj);
358 for (i=0; i < PyUnicode_GET_LENGTH(lineobj); i++) {
359 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
360 if (ch != ' ' && ch != '\t' && ch != '\014')
361 break;
362 }
363 if (i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 PyObject *truncated;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200365 truncated = PyUnicode_Substring(lineobj, i, PyUnicode_GET_LENGTH(lineobj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (truncated) {
367 Py_DECREF(lineobj);
368 lineobj = truncated;
369 } else {
370 PyErr_Clear();
371 }
372 }
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 /* Write some spaces before the line */
375 strcpy(buf, " ");
376 assert (strlen(buf) == 10);
377 while (indent > 0) {
Benjamin Peterson0f9b7d32013-07-21 13:29:37 -0700378 if (indent < 10)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 buf[indent] = '\0';
380 err = PyFile_WriteString(buf, f);
381 if (err != 0)
382 break;
383 indent -= 10;
384 }
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 /* finally display the line */
387 if (err == 0)
388 err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW);
389 Py_DECREF(lineobj);
390 if (err == 0)
391 err = PyFile_WriteString("\n", f);
392 return err;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000393}
394
Guido van Rossum7e8d26d1997-05-22 22:35:47 +0000395static int
Victor Stinner0fe25a42010-06-17 23:08:50 +0000396tb_displayline(PyObject *f, PyObject *filename, int lineno, PyObject *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000397{
Victor Stinner0fe25a42010-06-17 23:08:50 +0000398 int err;
399 PyObject *line;
Christian Heimes33fe8092008-04-13 13:53:33 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (filename == NULL || name == NULL)
402 return -1;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000403 line = PyUnicode_FromFormat(" File \"%U\", line %d, in %U\n",
404 filename, lineno, name);
405 if (line == NULL)
406 return -1;
407 err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
408 Py_DECREF(line);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (err != 0)
410 return err;
Kristján Valur Jónssonc5963d32012-07-19 21:02:03 +0000411 /* ignore errors since we can't report them, can we? */
412 if (_Py_DisplaySourceLine(f, filename, lineno, 4))
413 PyErr_Clear();
414 return err;
Christian Heimes33fe8092008-04-13 13:53:33 +0000415}
416
417static int
418tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit)
419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 int err = 0;
421 long depth = 0;
Nick Coghland0034232016-08-15 13:11:34 +1000422 PyObject *last_file = NULL;
423 int last_line = -1;
424 PyObject *last_name = NULL;
425 long cnt = 0;
426 PyObject *line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyTracebackObject *tb1 = tb;
428 while (tb1 != NULL) {
429 depth++;
430 tb1 = tb1->tb_next;
431 }
432 while (tb != NULL && err == 0) {
433 if (depth <= limit) {
Nick Coghland0034232016-08-15 13:11:34 +1000434 if (last_file != NULL &&
435 tb->tb_frame->f_code->co_filename == last_file &&
436 last_line != -1 && tb->tb_lineno == last_line &&
437 last_name != NULL &&
438 tb->tb_frame->f_code->co_name == last_name) {
439 cnt++;
440 } else {
441 if (cnt > 3) {
442 line = PyUnicode_FromFormat(
443 " [Previous line repeated %d more times]\n", cnt-3);
444 err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
Victor Stinnera88b2f42016-08-20 03:05:13 +0200445 Py_DECREF(line);
Nick Coghland0034232016-08-15 13:11:34 +1000446 }
447 last_file = tb->tb_frame->f_code->co_filename;
448 last_line = tb->tb_lineno;
449 last_name = tb->tb_frame->f_code->co_name;
450 cnt = 0;
451 }
452 if (cnt < 3)
453 err = tb_displayline(f,
454 tb->tb_frame->f_code->co_filename,
455 tb->tb_lineno,
456 tb->tb_frame->f_code->co_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 }
458 depth--;
459 tb = tb->tb_next;
460 if (err == 0)
461 err = PyErr_CheckSignals();
462 }
Nick Coghland0034232016-08-15 13:11:34 +1000463 if (cnt > 3) {
464 line = PyUnicode_FromFormat(
465 " [Previous line repeated %d more times]\n", cnt-3);
466 err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
Victor Stinnera88b2f42016-08-20 03:05:13 +0200467 Py_DECREF(line);
Nick Coghland0034232016-08-15 13:11:34 +1000468 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 return err;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000470}
471
Christian Heimes0fbab7f2007-12-04 21:55:18 +0000472#define PyTraceBack_LIMIT 1000
473
Guido van Rossum3f5da241990-12-20 15:06:42 +0000474int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000475PyTraceBack_Print(PyObject *v, PyObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 int err;
478 PyObject *limitv;
479 long limit = PyTraceBack_LIMIT;
Christian Heimes0fbab7f2007-12-04 21:55:18 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (v == NULL)
482 return 0;
483 if (!PyTraceBack_Check(v)) {
484 PyErr_BadInternalCall();
485 return -1;
486 }
487 limitv = PySys_GetObject("tracebacklimit");
488 if (limitv) {
489 PyObject *exc_type, *exc_value, *exc_tb;
Christian Heimes0fbab7f2007-12-04 21:55:18 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
492 limit = PyLong_AsLong(limitv);
493 if (limit == -1 && PyErr_Occurred()) {
494 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
495 limit = PyTraceBack_LIMIT;
496 }
497 else {
498 Py_XDECREF(exc_type);
499 Py_XDECREF(exc_value);
500 Py_XDECREF(exc_tb);
501 return 0;
502 }
503 }
504 else if (limit <= 0) {
505 limit = PyTraceBack_LIMIT;
506 }
507 PyErr_Restore(exc_type, exc_value, exc_tb);
508 }
509 err = PyFile_WriteString("Traceback (most recent call last):\n", f);
510 if (!err)
511 err = tb_printinternal((PyTracebackObject *)v, f, limit);
512 return err;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000513}
Victor Stinner024e37a2011-03-31 01:31:06 +0200514
515/* Reverse a string. For example, "abcd" becomes "dcba".
516
517 This function is signal safe. */
518
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100519void
520_Py_DumpDecimal(int fd, unsigned long value)
Victor Stinner024e37a2011-03-31 01:31:06 +0200521{
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100522 /* maximum number of characters required for output of %lld or %p.
523 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
524 plus 1 for the null byte. 53/22 is an upper bound for log10(256). */
525 char buffer[1 + (sizeof(unsigned long)*53-1) / 22 + 1];
526 char *ptr, *end;
Victor Stinner024e37a2011-03-31 01:31:06 +0200527
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100528 end = &buffer[Py_ARRAY_LENGTH(buffer) - 1];
529 ptr = end;
530 *ptr = '\0';
Victor Stinner024e37a2011-03-31 01:31:06 +0200531 do {
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100532 --ptr;
533 assert(ptr >= buffer);
534 *ptr = '0' + (value % 10);
Victor Stinner024e37a2011-03-31 01:31:06 +0200535 value /= 10;
Victor Stinner024e37a2011-03-31 01:31:06 +0200536 } while (value);
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100537
538 _Py_write_noraise(fd, ptr, end - ptr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200539}
540
Guido van Rossum7be5d7d2013-10-20 18:21:02 -0700541/* Format an integer in range [0; 0xffffffff] to hexadecimal of 'width' digits,
Victor Stinner024e37a2011-03-31 01:31:06 +0200542 and write it into the file fd.
543
544 This function is signal safe. */
545
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100546void
547_Py_DumpHexadecimal(int fd, unsigned long value, Py_ssize_t width)
Victor Stinner024e37a2011-03-31 01:31:06 +0200548{
Victor Stinner013024e2016-03-16 09:43:14 +0100549 char buffer[sizeof(unsigned long) * 2 + 1], *ptr, *end;
550 const Py_ssize_t size = Py_ARRAY_LENGTH(buffer) - 1;
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100551
552 if (width > size)
553 width = size;
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100554 /* it's ok if width is negative */
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100555
Victor Stinner013024e2016-03-16 09:43:14 +0100556 end = &buffer[size];
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100557 ptr = end;
558 *ptr = '\0';
Victor Stinner024e37a2011-03-31 01:31:06 +0200559 do {
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100560 --ptr;
561 assert(ptr >= buffer);
562 *ptr = Py_hexdigits[value & 15];
Victor Stinner024e37a2011-03-31 01:31:06 +0200563 value >>= 4;
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100564 } while ((end - ptr) < width || value);
565
566 _Py_write_noraise(fd, ptr, end - ptr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200567}
568
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100569void
570_Py_DumpASCII(int fd, PyObject *text)
Victor Stinner024e37a2011-03-31 01:31:06 +0200571{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200572 PyASCIIObject *ascii = (PyASCIIObject *)text;
Victor Stinner024e37a2011-03-31 01:31:06 +0200573 Py_ssize_t i, size;
574 int truncated;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200575 int kind;
Victor Stinnera336de72011-10-05 22:44:12 +0200576 void *data = NULL;
577 wchar_t *wstr = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200578 Py_UCS4 ch;
Victor Stinner024e37a2011-03-31 01:31:06 +0200579
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100580 if (!PyUnicode_Check(text))
581 return;
582
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200583 size = ascii->length;
584 kind = ascii->state.kind;
Victor Stinner1c3069a2016-03-23 16:10:07 +0100585 if (kind == PyUnicode_WCHAR_KIND) {
586 wstr = ((PyASCIIObject *)text)->wstr;
587 if (wstr == NULL)
588 return;
589 size = ((PyCompactUnicodeObject *)text)->wstr_length;
590 }
591 else if (ascii->state.compact) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200592 if (ascii->state.ascii)
593 data = ((PyASCIIObject*)text) + 1;
594 else
595 data = ((PyCompactUnicodeObject*)text) + 1;
596 }
Victor Stinner1c3069a2016-03-23 16:10:07 +0100597 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200598 data = ((PyUnicodeObject *)text)->data.any;
599 if (data == NULL)
600 return;
601 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200602
603 if (MAX_STRING_LENGTH < size) {
604 size = MAX_STRING_LENGTH;
605 truncated = 1;
606 }
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100607 else {
Victor Stinner024e37a2011-03-31 01:31:06 +0200608 truncated = 0;
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100609 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200610
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200611 for (i=0; i < size; i++) {
Victor Stinnera336de72011-10-05 22:44:12 +0200612 if (kind != PyUnicode_WCHAR_KIND)
613 ch = PyUnicode_READ(kind, data, i);
614 else
615 ch = wstr[i];
Victor Stinnerb86f08f2014-10-03 14:18:09 +0200616 if (' ' <= ch && ch <= 126) {
617 /* printable ASCII character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200618 char c = (char)ch;
Victor Stinner97f86b82015-04-01 18:38:01 +0200619 _Py_write_noraise(fd, &c, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200620 }
Victor Stinnerb86f08f2014-10-03 14:18:09 +0200621 else if (ch <= 0xff) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200622 PUTS(fd, "\\x");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100623 _Py_DumpHexadecimal(fd, ch, 2);
Victor Stinner024e37a2011-03-31 01:31:06 +0200624 }
Victor Stinnerb86f08f2014-10-03 14:18:09 +0200625 else if (ch <= 0xffff) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200626 PUTS(fd, "\\u");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100627 _Py_DumpHexadecimal(fd, ch, 4);
Victor Stinner024e37a2011-03-31 01:31:06 +0200628 }
629 else {
630 PUTS(fd, "\\U");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100631 _Py_DumpHexadecimal(fd, ch, 8);
Victor Stinner024e37a2011-03-31 01:31:06 +0200632 }
633 }
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100634 if (truncated) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200635 PUTS(fd, "...");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100636 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200637}
638
639/* Write a frame into the file fd: "File "xxx", line xxx in xxx".
640
641 This function is signal safe. */
642
643static void
644dump_frame(int fd, PyFrameObject *frame)
645{
646 PyCodeObject *code;
647 int lineno;
648
649 code = frame->f_code;
650 PUTS(fd, " File ");
651 if (code != NULL && code->co_filename != NULL
652 && PyUnicode_Check(code->co_filename))
653 {
Victor Stinner97f86b82015-04-01 18:38:01 +0200654 PUTS(fd, "\"");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100655 _Py_DumpASCII(fd, code->co_filename);
Victor Stinner97f86b82015-04-01 18:38:01 +0200656 PUTS(fd, "\"");
Victor Stinner024e37a2011-03-31 01:31:06 +0200657 } else {
658 PUTS(fd, "???");
659 }
660
661 /* PyFrame_GetLineNumber() was introduced in Python 2.7.0 and 3.2.0 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200662 lineno = PyCode_Addr2Line(code, frame->f_lasti);
Victor Stinner024e37a2011-03-31 01:31:06 +0200663 PUTS(fd, ", line ");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100664 if (lineno >= 0) {
665 _Py_DumpDecimal(fd, (unsigned long)lineno);
666 }
667 else {
668 PUTS(fd, "???");
669 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200670 PUTS(fd, " in ");
671
672 if (code != NULL && code->co_name != NULL
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100673 && PyUnicode_Check(code->co_name)) {
674 _Py_DumpASCII(fd, code->co_name);
675 }
676 else {
Victor Stinner024e37a2011-03-31 01:31:06 +0200677 PUTS(fd, "???");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100678 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200679
Victor Stinner97f86b82015-04-01 18:38:01 +0200680 PUTS(fd, "\n");
Victor Stinner024e37a2011-03-31 01:31:06 +0200681}
682
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200683static void
Victor Stinner024e37a2011-03-31 01:31:06 +0200684dump_traceback(int fd, PyThreadState *tstate, int write_header)
685{
686 PyFrameObject *frame;
687 unsigned int depth;
688
Victor Stinner024e37a2011-03-31 01:31:06 +0200689 if (write_header)
Guido van Rossum7be5d7d2013-10-20 18:21:02 -0700690 PUTS(fd, "Stack (most recent call first):\n");
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200691
692 frame = _PyThreadState_GetFrame(tstate);
693 if (frame == NULL)
694 return;
695
Victor Stinner024e37a2011-03-31 01:31:06 +0200696 depth = 0;
697 while (frame != NULL) {
698 if (MAX_FRAME_DEPTH <= depth) {
699 PUTS(fd, " ...\n");
700 break;
701 }
702 if (!PyFrame_Check(frame))
703 break;
704 dump_frame(fd, frame);
705 frame = frame->f_back;
706 depth++;
707 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200708}
709
Victor Stinner97f86b82015-04-01 18:38:01 +0200710/* Dump the traceback of a Python thread into fd. Use write() to write the
711 traceback and retry if write() is interrupted by a signal (failed with
712 EINTR), but don't call the Python signal handler.
713
714 The caller is responsible to call PyErr_CheckSignals() to call Python signal
715 handlers if signals were received. */
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200716void
Victor Stinner024e37a2011-03-31 01:31:06 +0200717_Py_DumpTraceback(int fd, PyThreadState *tstate)
718{
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200719 dump_traceback(fd, tstate, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200720}
721
722/* Write the thread identifier into the file 'fd': "Current thread 0xHHHH:\" if
723 is_current is true, "Thread 0xHHHH:\n" otherwise.
724
725 This function is signal safe. */
726
727static void
728write_thread_id(int fd, PyThreadState *tstate, int is_current)
729{
730 if (is_current)
731 PUTS(fd, "Current thread 0x");
732 else
733 PUTS(fd, "Thread 0x");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100734 _Py_DumpHexadecimal(fd,
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200735 tstate->thread_id,
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100736 sizeof(unsigned long) * 2);
Guido van Rossum7be5d7d2013-10-20 18:21:02 -0700737 PUTS(fd, " (most recent call first):\n");
Victor Stinner024e37a2011-03-31 01:31:06 +0200738}
739
Victor Stinner97f86b82015-04-01 18:38:01 +0200740/* Dump the traceback of all Python threads into fd. Use write() to write the
741 traceback and retry if write() is interrupted by a signal (failed with
742 EINTR), but don't call the Python signal handler.
743
744 The caller is responsible to call PyErr_CheckSignals() to call Python signal
745 handlers if signals were received. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200746const char*
747_Py_DumpTracebackThreads(int fd, PyInterpreterState *interp,
Victor Stinner861d9ab2016-03-16 22:45:24 +0100748 PyThreadState *current_tstate)
Victor Stinner024e37a2011-03-31 01:31:06 +0200749{
750 PyThreadState *tstate;
751 unsigned int nthreads;
752
Victor Stinner861d9ab2016-03-16 22:45:24 +0100753 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 }
Victor Stinner861d9ab2016-03-16 22:45:24 +0100780 assert(interp != NULL);
781
Victor Stinner024e37a2011-03-31 01:31:06 +0200782 /* Get the current interpreter from the current thread */
783 tstate = PyInterpreterState_ThreadHead(interp);
784 if (tstate == NULL)
785 return "unable to get the thread head state";
786
787 /* Dump the traceback of each thread */
788 tstate = PyInterpreterState_ThreadHead(interp);
789 nthreads = 0;
Steve Dower8fc89802015-04-12 00:26:27 -0400790 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner024e37a2011-03-31 01:31:06 +0200791 do
792 {
793 if (nthreads != 0)
Victor Stinner97f86b82015-04-01 18:38:01 +0200794 PUTS(fd, "\n");
Victor Stinner024e37a2011-03-31 01:31:06 +0200795 if (nthreads >= MAX_NTHREADS) {
796 PUTS(fd, "...\n");
797 break;
798 }
Victor Stinner861d9ab2016-03-16 22:45:24 +0100799 write_thread_id(fd, tstate, tstate == current_tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +0200800 dump_traceback(fd, tstate, 0);
801 tstate = PyThreadState_Next(tstate);
802 nthreads++;
803 } while (tstate != NULL);
Steve Dower8fc89802015-04-12 00:26:27 -0400804 _Py_END_SUPPRESS_IPH
Victor Stinner024e37a2011-03-31 01:31:06 +0200805
806 return NULL;
807}
808