blob: b33156eaa7902d269f8b440a1456873904892ead [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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 PyThreadState *tstate = PyThreadState_GET();
136 PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback;
137 PyTracebackObject *tb = newtracebackobject(oldtb, frame);
138 if (tb == NULL)
139 return -1;
140 tstate->curexc_traceback = (PyObject *)tb;
141 Py_XDECREF(oldtb);
142 return 0;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000143}
144
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200145/* Insert a frame into the traceback for (funcname, filename, lineno). */
Serhiy Storchaka73c95f12015-06-21 15:59:46 +0300146void _PyTraceback_Add(const char *funcname, const char *filename, int lineno)
Antoine Pitrou0ddbf472014-10-08 20:00:09 +0200147{
148 PyObject *globals = NULL;
149 PyCodeObject *code = NULL;
150 PyFrameObject *frame = NULL;
151 PyObject *exception, *value, *tb;
152
153 /* Save and clear the current exception. Python functions must not be
154 called with an exception set. Calling Python functions happens when
155 the codec of the filesystem encoding is implemented in pure Python. */
156 PyErr_Fetch(&exception, &value, &tb);
157
158 globals = PyDict_New();
159 if (!globals)
160 goto done;
161 code = PyCode_NewEmpty(filename, funcname, lineno);
162 if (!code)
163 goto done;
164 frame = PyFrame_New(PyThreadState_Get(), code, globals, NULL);
165 if (!frame)
166 goto done;
167 frame->f_lineno = lineno;
168
169 PyErr_Restore(exception, value, tb);
170 PyTraceBack_Here(frame);
171
172done:
173 Py_XDECREF(globals);
174 Py_XDECREF(code);
175 Py_XDECREF(frame);
176}
177
Victor Stinner0fe25a42010-06-17 23:08:50 +0000178static PyObject *
179_Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io)
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000180{
Victor Stinner0fe25a42010-06-17 23:08:50 +0000181 Py_ssize_t i;
182 PyObject *binary;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 PyObject *v;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000184 Py_ssize_t npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 size_t taillen;
186 PyObject *syspath;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000187 PyObject *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 const char* tail;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000189 PyObject *filebytes;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000190 const char* filepath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 Py_ssize_t len;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000192 PyObject* result;
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000193
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000194 filebytes = PyUnicode_EncodeFSDefault(filename);
195 if (filebytes == NULL) {
Victor Stinner0fe25a42010-06-17 23:08:50 +0000196 PyErr_Clear();
197 return NULL;
198 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000199 filepath = PyBytes_AS_STRING(filebytes);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 /* Search tail of filename in sys.path before giving up */
Victor Stinner0fe25a42010-06-17 23:08:50 +0000202 tail = strrchr(filepath, SEP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 if (tail == NULL)
Victor Stinner0fe25a42010-06-17 23:08:50 +0000204 tail = filepath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 else
206 tail++;
207 taillen = strlen(tail);
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000208
Victor Stinnerbd303c12013-11-07 23:07:29 +0100209 syspath = _PySys_GetObjectId(&PyId_path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (syspath == NULL || !PyList_Check(syspath))
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000211 goto error;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000212 npath = PyList_Size(syspath);
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 for (i = 0; i < npath; i++) {
215 v = PyList_GetItem(syspath, i);
216 if (v == NULL) {
217 PyErr_Clear();
218 break;
219 }
220 if (!PyUnicode_Check(v))
221 continue;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000222 path = PyUnicode_EncodeFSDefault(v);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000223 if (path == NULL) {
224 PyErr_Clear();
225 continue;
226 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000227 len = PyBytes_GET_SIZE(path);
228 if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) {
229 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 continue; /* Too long */
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000231 }
232 strcpy(namebuf, PyBytes_AS_STRING(path));
233 Py_DECREF(path);
Victor Stinner98ea54c2014-08-15 23:30:40 +0200234 if (strlen(namebuf) != (size_t)len)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 continue; /* v contains '\0' */
236 if (len > 0 && namebuf[len-1] != SEP)
237 namebuf[len++] = SEP;
238 strcpy(namebuf+len, tail);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000239
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200240 binary = _PyObject_CallMethodId(io, &PyId_open, "ss", namebuf, "rb");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000241 if (binary != NULL) {
242 result = binary;
243 goto finally;
244 }
Victor Stinner0fe25a42010-06-17 23:08:50 +0000245 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000247 goto error;
248
249error:
250 result = NULL;
251finally:
252 Py_DECREF(filebytes);
253 return result;
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000254}
255
Christian Heimes33fe8092008-04-13 13:53:33 +0000256int
Victor Stinner0fe25a42010-06-17 23:08:50 +0000257_Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 int err = 0;
260 int fd;
261 int i;
262 char *found_encoding;
263 char *encoding;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000264 PyObject *io;
265 PyObject *binary;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 PyObject *fob = NULL;
267 PyObject *lineobj = NULL;
Antoine Pitroub86680e2010-10-14 21:15:17 +0000268 PyObject *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 char buf[MAXPATHLEN+1];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200270 int kind;
271 void *data;
Christian Heimes679db4a2008-01-18 09:56:22 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 /* open the file */
274 if (filename == NULL)
275 return 0;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000276
277 io = PyImport_ImportModuleNoBlock("io");
278 if (io == NULL)
279 return -1;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200280 binary = _PyObject_CallMethodId(io, &PyId_open, "Os", filename, "rb");
Victor Stinner0fe25a42010-06-17 23:08:50 +0000281
282 if (binary == NULL) {
Victor Stinnerceceaa02013-07-16 00:32:14 +0200283 PyErr_Clear();
284
Victor Stinner0fe25a42010-06-17 23:08:50 +0000285 binary = _Py_FindSourceFile(filename, buf, sizeof(buf), io);
286 if (binary == NULL) {
287 Py_DECREF(io);
Victor Stinnerceceaa02013-07-16 00:32:14 +0200288 return -1;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 /* use the right encoding to decode the file as unicode */
Victor Stinner0fe25a42010-06-17 23:08:50 +0000293 fd = PyObject_AsFileDescriptor(binary);
Christian Heimes8c077bc2013-07-21 01:53:10 +0200294 if (fd < 0) {
295 Py_DECREF(io);
296 Py_DECREF(binary);
Benjamin Peterson04b01dc2013-07-21 13:26:13 -0700297 return 0;
Christian Heimes8c077bc2013-07-21 01:53:10 +0200298 }
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200299 found_encoding = PyTokenizer_FindEncodingFilename(fd, filename);
Victor Stinner5272fa92013-12-19 13:39:32 +0100300 if (found_encoding == NULL)
301 PyErr_Clear();
Victor Stinner0fe25a42010-06-17 23:08:50 +0000302 encoding = (found_encoding != NULL) ? found_encoding : "utf-8";
Christian Heimes1f347292013-07-21 02:12:35 +0200303 /* Reset position */
304 if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
305 Py_DECREF(io);
306 Py_DECREF(binary);
307 PyMem_FREE(found_encoding);
Benjamin Peterson04b01dc2013-07-21 13:26:13 -0700308 return 0;
Christian Heimes1f347292013-07-21 02:12:35 +0200309 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200310 fob = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "Os", binary, encoding);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000311 Py_DECREF(io);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 PyMem_FREE(found_encoding);
Victor Stinner0fe25a42010-06-17 23:08:50 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (fob == NULL) {
315 PyErr_Clear();
Victor Stinner81f241a2015-03-25 02:25:25 +0100316
317 res = _PyObject_CallMethodId(binary, &PyId_close, "");
318 Py_DECREF(binary);
319 if (res)
320 Py_DECREF(res);
321 else
322 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 return 0;
324 }
Victor Stinner81f241a2015-03-25 02:25:25 +0100325 Py_DECREF(binary);
Christian Heimes33fe8092008-04-13 13:53:33 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 /* get the line number lineno */
328 for (i = 0; i < lineno; i++) {
329 Py_XDECREF(lineobj);
330 lineobj = PyFile_GetLine(fob, -1);
331 if (!lineobj) {
Victor Stinner5e78f4d2014-10-30 10:17:27 +0100332 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 err = -1;
334 break;
335 }
336 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200337 res = _PyObject_CallMethodId(fob, &PyId_close, "");
Antoine Pitroub86680e2010-10-14 21:15:17 +0000338 if (res)
339 Py_DECREF(res);
340 else
341 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 Py_DECREF(fob);
343 if (!lineobj || !PyUnicode_Check(lineobj)) {
344 Py_XDECREF(lineobj);
345 return err;
346 }
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 /* remove the indentation of the line */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200349 kind = PyUnicode_KIND(lineobj);
350 data = PyUnicode_DATA(lineobj);
351 for (i=0; i < PyUnicode_GET_LENGTH(lineobj); i++) {
352 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
353 if (ch != ' ' && ch != '\t' && ch != '\014')
354 break;
355 }
356 if (i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 PyObject *truncated;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200358 truncated = PyUnicode_Substring(lineobj, i, PyUnicode_GET_LENGTH(lineobj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (truncated) {
360 Py_DECREF(lineobj);
361 lineobj = truncated;
362 } else {
363 PyErr_Clear();
364 }
365 }
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 /* Write some spaces before the line */
368 strcpy(buf, " ");
369 assert (strlen(buf) == 10);
370 while (indent > 0) {
Benjamin Peterson0f9b7d32013-07-21 13:29:37 -0700371 if (indent < 10)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 buf[indent] = '\0';
373 err = PyFile_WriteString(buf, f);
374 if (err != 0)
375 break;
376 indent -= 10;
377 }
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* finally display the line */
380 if (err == 0)
381 err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW);
382 Py_DECREF(lineobj);
383 if (err == 0)
384 err = PyFile_WriteString("\n", f);
385 return err;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000386}
387
Guido van Rossum7e8d26d1997-05-22 22:35:47 +0000388static int
Victor Stinner0fe25a42010-06-17 23:08:50 +0000389tb_displayline(PyObject *f, PyObject *filename, int lineno, PyObject *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000390{
Victor Stinner0fe25a42010-06-17 23:08:50 +0000391 int err;
392 PyObject *line;
Christian Heimes33fe8092008-04-13 13:53:33 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (filename == NULL || name == NULL)
395 return -1;
Victor Stinner0fe25a42010-06-17 23:08:50 +0000396 line = PyUnicode_FromFormat(" File \"%U\", line %d, in %U\n",
397 filename, lineno, name);
398 if (line == NULL)
399 return -1;
400 err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
401 Py_DECREF(line);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 if (err != 0)
403 return err;
Kristján Valur Jónssonc5963d32012-07-19 21:02:03 +0000404 /* ignore errors since we can't report them, can we? */
405 if (_Py_DisplaySourceLine(f, filename, lineno, 4))
406 PyErr_Clear();
407 return err;
Christian Heimes33fe8092008-04-13 13:53:33 +0000408}
409
410static int
411tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit)
412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 int err = 0;
414 long depth = 0;
Nick Coghland0034232016-08-15 13:11:34 +1000415 PyObject *last_file = NULL;
416 int last_line = -1;
417 PyObject *last_name = NULL;
418 long cnt = 0;
419 PyObject *line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyTracebackObject *tb1 = tb;
421 while (tb1 != NULL) {
422 depth++;
423 tb1 = tb1->tb_next;
424 }
425 while (tb != NULL && err == 0) {
426 if (depth <= limit) {
Nick Coghland0034232016-08-15 13:11:34 +1000427 if (last_file != NULL &&
428 tb->tb_frame->f_code->co_filename == last_file &&
429 last_line != -1 && tb->tb_lineno == last_line &&
430 last_name != NULL &&
431 tb->tb_frame->f_code->co_name == last_name) {
432 cnt++;
433 } else {
434 if (cnt > 3) {
435 line = PyUnicode_FromFormat(
436 " [Previous line repeated %d more times]\n", cnt-3);
437 err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
Victor Stinnera88b2f42016-08-20 03:05:13 +0200438 Py_DECREF(line);
Nick Coghland0034232016-08-15 13:11:34 +1000439 }
440 last_file = tb->tb_frame->f_code->co_filename;
441 last_line = tb->tb_lineno;
442 last_name = tb->tb_frame->f_code->co_name;
443 cnt = 0;
444 }
445 if (cnt < 3)
446 err = tb_displayline(f,
447 tb->tb_frame->f_code->co_filename,
448 tb->tb_lineno,
449 tb->tb_frame->f_code->co_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 }
451 depth--;
452 tb = tb->tb_next;
453 if (err == 0)
454 err = PyErr_CheckSignals();
455 }
Nick Coghland0034232016-08-15 13:11:34 +1000456 if (cnt > 3) {
457 line = PyUnicode_FromFormat(
458 " [Previous line repeated %d more times]\n", cnt-3);
459 err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
Victor Stinnera88b2f42016-08-20 03:05:13 +0200460 Py_DECREF(line);
Nick Coghland0034232016-08-15 13:11:34 +1000461 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 return err;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000463}
464
Christian Heimes0fbab7f2007-12-04 21:55:18 +0000465#define PyTraceBack_LIMIT 1000
466
Guido van Rossum3f5da241990-12-20 15:06:42 +0000467int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000468PyTraceBack_Print(PyObject *v, PyObject *f)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 int err;
471 PyObject *limitv;
472 long limit = PyTraceBack_LIMIT;
Christian Heimes0fbab7f2007-12-04 21:55:18 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (v == NULL)
475 return 0;
476 if (!PyTraceBack_Check(v)) {
477 PyErr_BadInternalCall();
478 return -1;
479 }
480 limitv = PySys_GetObject("tracebacklimit");
481 if (limitv) {
482 PyObject *exc_type, *exc_value, *exc_tb;
Christian Heimes0fbab7f2007-12-04 21:55:18 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
485 limit = PyLong_AsLong(limitv);
486 if (limit == -1 && PyErr_Occurred()) {
487 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
488 limit = PyTraceBack_LIMIT;
489 }
490 else {
491 Py_XDECREF(exc_type);
492 Py_XDECREF(exc_value);
493 Py_XDECREF(exc_tb);
494 return 0;
495 }
496 }
497 else if (limit <= 0) {
498 limit = PyTraceBack_LIMIT;
499 }
500 PyErr_Restore(exc_type, exc_value, exc_tb);
501 }
502 err = PyFile_WriteString("Traceback (most recent call last):\n", f);
503 if (!err)
504 err = tb_printinternal((PyTracebackObject *)v, f, limit);
505 return err;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000506}
Victor Stinner024e37a2011-03-31 01:31:06 +0200507
508/* Reverse a string. For example, "abcd" becomes "dcba".
509
510 This function is signal safe. */
511
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100512void
513_Py_DumpDecimal(int fd, unsigned long value)
Victor Stinner024e37a2011-03-31 01:31:06 +0200514{
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100515 /* maximum number of characters required for output of %lld or %p.
516 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
517 plus 1 for the null byte. 53/22 is an upper bound for log10(256). */
518 char buffer[1 + (sizeof(unsigned long)*53-1) / 22 + 1];
519 char *ptr, *end;
Victor Stinner024e37a2011-03-31 01:31:06 +0200520
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100521 end = &buffer[Py_ARRAY_LENGTH(buffer) - 1];
522 ptr = end;
523 *ptr = '\0';
Victor Stinner024e37a2011-03-31 01:31:06 +0200524 do {
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100525 --ptr;
526 assert(ptr >= buffer);
527 *ptr = '0' + (value % 10);
Victor Stinner024e37a2011-03-31 01:31:06 +0200528 value /= 10;
Victor Stinner024e37a2011-03-31 01:31:06 +0200529 } while (value);
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100530
531 _Py_write_noraise(fd, ptr, end - ptr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200532}
533
Guido van Rossum7be5d7d2013-10-20 18:21:02 -0700534/* Format an integer in range [0; 0xffffffff] to hexadecimal of 'width' digits,
Victor Stinner024e37a2011-03-31 01:31:06 +0200535 and write it into the file fd.
536
537 This function is signal safe. */
538
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100539void
540_Py_DumpHexadecimal(int fd, unsigned long value, Py_ssize_t width)
Victor Stinner024e37a2011-03-31 01:31:06 +0200541{
Victor Stinner013024e2016-03-16 09:43:14 +0100542 char buffer[sizeof(unsigned long) * 2 + 1], *ptr, *end;
543 const Py_ssize_t size = Py_ARRAY_LENGTH(buffer) - 1;
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100544
545 if (width > size)
546 width = size;
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100547 /* it's ok if width is negative */
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100548
Victor Stinner013024e2016-03-16 09:43:14 +0100549 end = &buffer[size];
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100550 ptr = end;
551 *ptr = '\0';
Victor Stinner024e37a2011-03-31 01:31:06 +0200552 do {
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100553 --ptr;
554 assert(ptr >= buffer);
555 *ptr = Py_hexdigits[value & 15];
Victor Stinner024e37a2011-03-31 01:31:06 +0200556 value >>= 4;
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100557 } while ((end - ptr) < width || value);
558
559 _Py_write_noraise(fd, ptr, end - ptr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200560}
561
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100562void
563_Py_DumpASCII(int fd, PyObject *text)
Victor Stinner024e37a2011-03-31 01:31:06 +0200564{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200565 PyASCIIObject *ascii = (PyASCIIObject *)text;
Victor Stinner024e37a2011-03-31 01:31:06 +0200566 Py_ssize_t i, size;
567 int truncated;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200568 int kind;
Victor Stinnera336de72011-10-05 22:44:12 +0200569 void *data = NULL;
570 wchar_t *wstr = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200571 Py_UCS4 ch;
Victor Stinner024e37a2011-03-31 01:31:06 +0200572
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100573 if (!PyUnicode_Check(text))
574 return;
575
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200576 size = ascii->length;
577 kind = ascii->state.kind;
Victor Stinner1c3069a2016-03-23 16:10:07 +0100578 if (kind == PyUnicode_WCHAR_KIND) {
579 wstr = ((PyASCIIObject *)text)->wstr;
580 if (wstr == NULL)
581 return;
582 size = ((PyCompactUnicodeObject *)text)->wstr_length;
583 }
584 else if (ascii->state.compact) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200585 if (ascii->state.ascii)
586 data = ((PyASCIIObject*)text) + 1;
587 else
588 data = ((PyCompactUnicodeObject*)text) + 1;
589 }
Victor Stinner1c3069a2016-03-23 16:10:07 +0100590 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200591 data = ((PyUnicodeObject *)text)->data.any;
592 if (data == NULL)
593 return;
594 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200595
596 if (MAX_STRING_LENGTH < size) {
597 size = MAX_STRING_LENGTH;
598 truncated = 1;
599 }
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100600 else {
Victor Stinner024e37a2011-03-31 01:31:06 +0200601 truncated = 0;
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100602 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200603
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200604 for (i=0; i < size; i++) {
Victor Stinnera336de72011-10-05 22:44:12 +0200605 if (kind != PyUnicode_WCHAR_KIND)
606 ch = PyUnicode_READ(kind, data, i);
607 else
608 ch = wstr[i];
Victor Stinnerb86f08f2014-10-03 14:18:09 +0200609 if (' ' <= ch && ch <= 126) {
610 /* printable ASCII character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200611 char c = (char)ch;
Victor Stinner97f86b82015-04-01 18:38:01 +0200612 _Py_write_noraise(fd, &c, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200613 }
Victor Stinnerb86f08f2014-10-03 14:18:09 +0200614 else if (ch <= 0xff) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200615 PUTS(fd, "\\x");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100616 _Py_DumpHexadecimal(fd, ch, 2);
Victor Stinner024e37a2011-03-31 01:31:06 +0200617 }
Victor Stinnerb86f08f2014-10-03 14:18:09 +0200618 else if (ch <= 0xffff) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200619 PUTS(fd, "\\u");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100620 _Py_DumpHexadecimal(fd, ch, 4);
Victor Stinner024e37a2011-03-31 01:31:06 +0200621 }
622 else {
623 PUTS(fd, "\\U");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100624 _Py_DumpHexadecimal(fd, ch, 8);
Victor Stinner024e37a2011-03-31 01:31:06 +0200625 }
626 }
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100627 if (truncated) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200628 PUTS(fd, "...");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100629 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200630}
631
632/* Write a frame into the file fd: "File "xxx", line xxx in xxx".
633
634 This function is signal safe. */
635
636static void
637dump_frame(int fd, PyFrameObject *frame)
638{
639 PyCodeObject *code;
640 int lineno;
641
642 code = frame->f_code;
643 PUTS(fd, " File ");
644 if (code != NULL && code->co_filename != NULL
645 && PyUnicode_Check(code->co_filename))
646 {
Victor Stinner97f86b82015-04-01 18:38:01 +0200647 PUTS(fd, "\"");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100648 _Py_DumpASCII(fd, code->co_filename);
Victor Stinner97f86b82015-04-01 18:38:01 +0200649 PUTS(fd, "\"");
Victor Stinner024e37a2011-03-31 01:31:06 +0200650 } else {
651 PUTS(fd, "???");
652 }
653
654 /* PyFrame_GetLineNumber() was introduced in Python 2.7.0 and 3.2.0 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200655 lineno = PyCode_Addr2Line(code, frame->f_lasti);
Victor Stinner024e37a2011-03-31 01:31:06 +0200656 PUTS(fd, ", line ");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100657 if (lineno >= 0) {
658 _Py_DumpDecimal(fd, (unsigned long)lineno);
659 }
660 else {
661 PUTS(fd, "???");
662 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200663 PUTS(fd, " in ");
664
665 if (code != NULL && code->co_name != NULL
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100666 && PyUnicode_Check(code->co_name)) {
667 _Py_DumpASCII(fd, code->co_name);
668 }
669 else {
Victor Stinner024e37a2011-03-31 01:31:06 +0200670 PUTS(fd, "???");
Victor Stinner89e7cdc2016-03-15 21:49:37 +0100671 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200672
Victor Stinner97f86b82015-04-01 18:38:01 +0200673 PUTS(fd, "\n");
Victor Stinner024e37a2011-03-31 01:31:06 +0200674}
675
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200676static void
Victor Stinner024e37a2011-03-31 01:31:06 +0200677dump_traceback(int fd, PyThreadState *tstate, int write_header)
678{
679 PyFrameObject *frame;
680 unsigned int depth;
681
Victor Stinner024e37a2011-03-31 01:31:06 +0200682 if (write_header)
Guido van Rossum7be5d7d2013-10-20 18:21:02 -0700683 PUTS(fd, "Stack (most recent call first):\n");
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200684
685 frame = _PyThreadState_GetFrame(tstate);
686 if (frame == NULL)
687 return;
688
Victor Stinner024e37a2011-03-31 01:31:06 +0200689 depth = 0;
690 while (frame != NULL) {
691 if (MAX_FRAME_DEPTH <= depth) {
692 PUTS(fd, " ...\n");
693 break;
694 }
695 if (!PyFrame_Check(frame))
696 break;
697 dump_frame(fd, frame);
698 frame = frame->f_back;
699 depth++;
700 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200701}
702
Victor Stinner97f86b82015-04-01 18:38:01 +0200703/* Dump the traceback of a Python thread into fd. Use write() to write the
704 traceback and retry if write() is interrupted by a signal (failed with
705 EINTR), but don't call the Python signal handler.
706
707 The caller is responsible to call PyErr_CheckSignals() to call Python signal
708 handlers if signals were received. */
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200709void
Victor Stinner024e37a2011-03-31 01:31:06 +0200710_Py_DumpTraceback(int fd, PyThreadState *tstate)
711{
Victor Stinnerfcb88c42011-04-01 15:34:01 +0200712 dump_traceback(fd, tstate, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200713}
714
715/* Write the thread identifier into the file 'fd': "Current thread 0xHHHH:\" if
716 is_current is true, "Thread 0xHHHH:\n" otherwise.
717
718 This function is signal safe. */
719
720static void
721write_thread_id(int fd, PyThreadState *tstate, int is_current)
722{
723 if (is_current)
724 PUTS(fd, "Current thread 0x");
725 else
726 PUTS(fd, "Thread 0x");
Victor Stinnerbd31b7c2016-03-23 10:32:26 +0100727 _Py_DumpHexadecimal(fd,
728 (unsigned long)tstate->thread_id,
729 sizeof(unsigned long) * 2);
Guido van Rossum7be5d7d2013-10-20 18:21:02 -0700730 PUTS(fd, " (most recent call first):\n");
Victor Stinner024e37a2011-03-31 01:31:06 +0200731}
732
Victor Stinner97f86b82015-04-01 18:38:01 +0200733/* Dump the traceback of all Python threads into fd. Use write() to write the
734 traceback and retry if write() is interrupted by a signal (failed with
735 EINTR), but don't call the Python signal handler.
736
737 The caller is responsible to call PyErr_CheckSignals() to call Python signal
738 handlers if signals were received. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200739const char*
740_Py_DumpTracebackThreads(int fd, PyInterpreterState *interp,
Victor Stinner861d9ab2016-03-16 22:45:24 +0100741 PyThreadState *current_tstate)
Victor Stinner024e37a2011-03-31 01:31:06 +0200742{
743 PyThreadState *tstate;
744 unsigned int nthreads;
745
Victor Stinner861d9ab2016-03-16 22:45:24 +0100746#ifdef WITH_THREAD
747 if (current_tstate == NULL) {
748 /* _Py_DumpTracebackThreads() is called from signal handlers by
749 faulthandler.
750
751 SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals
752 and are thus delivered to the thread that caused the fault. Get the
753 Python thread state of the current thread.
754
755 PyThreadState_Get() doesn't give the state of the thread that caused
756 the fault if the thread released the GIL, and so this function
757 cannot be used. Read the thread local storage (TLS) instead: call
758 PyGILState_GetThisThreadState(). */
759 current_tstate = PyGILState_GetThisThreadState();
760 }
761
762 if (interp == NULL) {
763 if (current_tstate == NULL) {
764 interp = _PyGILState_GetInterpreterStateUnsafe();
765 if (interp == NULL) {
766 /* We need the interpreter state to get Python threads */
767 return "unable to get the interpreter state";
768 }
769 }
770 else {
771 interp = current_tstate->interp;
772 }
773 }
774#else
775 if (current_tstate == NULL) {
776 /* Call _PyThreadState_UncheckedGet() instead of PyThreadState_Get()
777 to not fail with a fatal error if the thread state is NULL. */
Berker Peksag531396c2016-06-17 13:25:01 +0300778 current_tstate = _PyThreadState_UncheckedGet();
Victor Stinner861d9ab2016-03-16 22:45:24 +0100779 }
780
781 if (interp == NULL) {
782 if (current_tstate == NULL) {
783 /* We need the interpreter state to get Python threads */
784 return "unable to get the interpreter state";
785 }
786 interp = current_tstate->interp;
787 }
788#endif
789 assert(interp != NULL);
790
Victor Stinner024e37a2011-03-31 01:31:06 +0200791 /* Get the current interpreter from the current thread */
792 tstate = PyInterpreterState_ThreadHead(interp);
793 if (tstate == NULL)
794 return "unable to get the thread head state";
795
796 /* Dump the traceback of each thread */
797 tstate = PyInterpreterState_ThreadHead(interp);
798 nthreads = 0;
Steve Dower8fc89802015-04-12 00:26:27 -0400799 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner024e37a2011-03-31 01:31:06 +0200800 do
801 {
802 if (nthreads != 0)
Victor Stinner97f86b82015-04-01 18:38:01 +0200803 PUTS(fd, "\n");
Victor Stinner024e37a2011-03-31 01:31:06 +0200804 if (nthreads >= MAX_NTHREADS) {
805 PUTS(fd, "...\n");
806 break;
807 }
Victor Stinner861d9ab2016-03-16 22:45:24 +0100808 write_thread_id(fd, tstate, tstate == current_tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +0200809 dump_traceback(fd, tstate, 0);
810 tstate = PyThreadState_Next(tstate);
811 nthreads++;
812 } while (tstate != NULL);
Steve Dower8fc89802015-04-12 00:26:27 -0400813 _Py_END_SUPPRESS_IPH
Victor Stinner024e37a2011-03-31 01:31:06 +0200814
815 return NULL;
816}
817