blob: a45ca3b18311dd7a530d04d8cfe01831ee37f2d6 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
Eric Snowc7ec9982017-05-23 23:00:52 -07002/* Top level execution of Python code (including in __main__) */
3
4/* To help control the interfaces between the startup, execution and
5 * shutdown code, the phases are split across separate modules (boostrap,
6 * pythonrun, shutdown)
7 */
8
9/* TODO: Cull includes following phase split */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010
Guido van Rossum82598051997-03-05 00:20:32 +000011#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +010014#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner4f98f462020-04-15 04:01:58 +020015
Victor Stinnere5014be2020-04-14 17:52:15 +020016#include "pycore_interp.h" // PyInterpreterState.importlib
Victor Stinner4f98f462020-04-15 04:01:58 +020017#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
18#include "pycore_pyerrors.h" // _PyErr_Fetch
19#include "pycore_pylifecycle.h" // _Py_UnhandledKeyboardInterrupt
Victor Stinnere5014be2020-04-14 17:52:15 +020020#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020021#include "pycore_sysmodule.h" // _PySys_Audit()
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022
Victor Stinner4f98f462020-04-15 04:01:58 +020023#include "token.h" // INDENT
Victor Stinner4f98f462020-04-15 04:01:58 +020024#include "errcode.h" // E_EOF
25#include "code.h" // PyCodeObject
26#include "symtable.h" // PySymtable_BuildObject()
Victor Stinner4f98f462020-04-15 04:01:58 +020027#include "marshal.h" // PyMarshal_ReadLongFromFile()
28
Lysandros Nikolaou564cd182020-06-22 02:47:46 +030029#include "parser_interface.h" // PyParser_ASTFrom*
Pablo Galindoc5fc1562020-04-22 23:29:27 +010030
Victor Stinner4f98f462020-04-15 04:01:58 +020031#ifdef MS_WINDOWS
32# include "malloc.h" // alloca()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000034
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000035#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020036# undef BYTE
37# include "windows.h"
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000038#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000039
Guido van Rossuma44823b1995-03-14 15:01:17 +000040
Victor Stinnerbd303c12013-11-07 23:07:29 +010041_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010042_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010043_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010044_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010045_Py_IDENTIFIER(last_type);
46_Py_IDENTIFIER(last_value);
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(ps1);
48_Py_IDENTIFIER(ps2);
49_Py_IDENTIFIER(stdin);
50_Py_IDENTIFIER(stdout);
51_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010052_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010053
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054#ifdef __cplusplus
55extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000056#endif
57
Guido van Rossumb73cc041993-11-01 16:28:59 +000058/* Forward */
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010060static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
xdegayee0582a32017-11-12 16:50:48 +010064static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000065
Guido van Rossum1984f1e1992-08-04 12:41:02 +000066/* Parse input from a file and execute it */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000067int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000068PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +000070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 if (filename == NULL)
72 filename = "???";
73 if (Py_FdIsInteractive(fp, filename)) {
74 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
75 if (closeit)
76 fclose(fp);
77 return err;
78 }
79 else
80 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000081}
82
83int
Victor Stinner95701bd2013-11-06 18:41:07 +010084PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +000085{
Victor Stinner95701bd2013-11-06 18:41:07 +010086 PyObject *filename, *v;
87 int ret, err;
Victor Stinner37d66d72019-06-13 02:16:41 +020088 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
xdegayee0582a32017-11-12 16:50:48 +010089 int nomem_count = 0;
Victor Stinner25420fe2017-11-20 18:12:22 -080090#ifdef Py_REF_DEBUG
Victor Stinnerda7933e2020-04-13 03:04:28 +020091 int show_ref_count = _Py_GetConfig()->show_ref_count;
Victor Stinner25420fe2017-11-20 18:12:22 -080092#endif
Jeremy Hylton9f324e92001-03-01 22:59:14 +000093
Victor Stinner95701bd2013-11-06 18:41:07 +010094 filename = PyUnicode_DecodeFSDefault(filename_str);
95 if (filename == NULL) {
96 PyErr_Print();
97 return -1;
98 }
99
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (flags == NULL) {
101 flags = &local_flags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 }
Victor Stinner09054372013-11-06 22:41:44 +0100103 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100105 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 Py_XDECREF(v);
107 }
Victor Stinner09054372013-11-06 22:41:44 +0100108 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100110 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 Py_XDECREF(v);
112 }
xdegayee0582a32017-11-12 16:50:48 +0100113 err = 0;
114 do {
115 ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
116 if (ret == -1 && PyErr_Occurred()) {
117 /* Prevent an endless loop after multiple consecutive MemoryErrors
118 * while still allowing an interactive command to fail with a
119 * MemoryError. */
120 if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
121 if (++nomem_count > 16) {
122 PyErr_Clear();
123 err = -1;
124 break;
125 }
126 } else {
127 nomem_count = 0;
128 }
129 PyErr_Print();
130 flush_io();
131 } else {
132 nomem_count = 0;
133 }
Eric Snowdae02762017-09-14 00:35:58 -0700134#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -0800135 if (show_ref_count) {
Eric Snowdae02762017-09-14 00:35:58 -0700136 _PyDebug_PrintTotalRefs();
Victor Stinner25420fe2017-11-20 18:12:22 -0800137 }
Eric Snowdae02762017-09-14 00:35:58 -0700138#endif
xdegayee0582a32017-11-12 16:50:48 +0100139 } while (ret != E_EOF);
Victor Stinner95701bd2013-11-06 18:41:07 +0100140 Py_DECREF(filename);
141 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000142}
143
xdegayee0582a32017-11-12 16:50:48 +0100144/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
145 * error on failure. */
146static int
147PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
148 PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000149{
Victor Stinner95701bd2013-11-06 18:41:07 +0100150 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 mod_ty mod;
152 PyArena *arena;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200153 const char *ps1 = "", *ps2 = "", *enc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200155 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +0100156 _Py_IDENTIFIER(__main__);
157
158 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
159 if (mod_name == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100160 return -1;
161 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400164 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +0100165 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400166 if (v && v != Py_None) {
167 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
168 if (oenc)
Serhiy Storchaka06515832016-11-20 09:13:07 +0200169 enc = PyUnicode_AsUTF8(oenc);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400170 if (!enc)
171 PyErr_Clear();
172 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 }
Victor Stinner09054372013-11-06 22:41:44 +0100174 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 if (v != NULL) {
176 v = PyObject_Str(v);
177 if (v == NULL)
178 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000179 else if (PyUnicode_Check(v)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200180 ps1 = PyUnicode_AsUTF8(v);
Victor Stinner386fe712010-05-19 00:34:15 +0000181 if (ps1 == NULL) {
182 PyErr_Clear();
183 ps1 = "";
184 }
185 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 }
Victor Stinner09054372013-11-06 22:41:44 +0100187 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (w != NULL) {
189 w = PyObject_Str(w);
190 if (w == NULL)
191 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000192 else if (PyUnicode_Check(w)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200193 ps2 = PyUnicode_AsUTF8(w);
Victor Stinner386fe712010-05-19 00:34:15 +0000194 if (ps2 == NULL) {
195 PyErr_Clear();
196 ps2 = "";
197 }
198 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 }
200 arena = PyArena_New();
201 if (arena == NULL) {
202 Py_XDECREF(v);
203 Py_XDECREF(w);
204 Py_XDECREF(oenc);
205 return -1;
206 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100207
Lysandros Nikolaou564cd182020-06-22 02:47:46 +0300208 mod = PyParser_ASTFromFileObject(fp, filename, enc, Py_single_input,
209 ps1, ps2, flags, &errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 Py_XDECREF(v);
212 Py_XDECREF(w);
213 Py_XDECREF(oenc);
214 if (mod == NULL) {
215 PyArena_Free(arena);
216 if (errcode == E_EOF) {
217 PyErr_Clear();
218 return E_EOF;
219 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 return -1;
221 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100222 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (m == NULL) {
224 PyArena_Free(arena);
225 return -1;
226 }
227 d = PyModule_GetDict(m);
228 v = run_mod(mod, filename, d, d, flags, arena);
229 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 return -1;
232 }
233 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200234 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000236}
237
Victor Stinner95701bd2013-11-06 18:41:07 +0100238int
xdegayee0582a32017-11-12 16:50:48 +0100239PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
240{
241 int res;
242
243 res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
244 if (res == -1) {
245 PyErr_Print();
246 flush_io();
247 }
248 return res;
249}
250
251int
Victor Stinner95701bd2013-11-06 18:41:07 +0100252PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
253{
254 PyObject *filename;
255 int res;
256
257 filename = PyUnicode_DecodeFSDefault(filename_str);
258 if (filename == NULL) {
259 PyErr_Print();
260 return -1;
261 }
262 res = PyRun_InteractiveOneObject(fp, filename, flags);
263 Py_DECREF(filename);
264 return res;
265}
266
267
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000268/* Check whether a file maybe a pyc file: Look at the extension,
269 the file type, and, if we may close it, at the first few bytes. */
270
271static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000272maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000273{
Brett Cannonf299abd2015-04-13 14:21:02 -0400274 if (strcmp(ext, ".pyc") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 /* Only look into the file if we are allowed to close it, since
278 it then should also be seekable. */
279 if (closeit) {
280 /* Read only two bytes of the magic. If the file was opened in
281 text mode, the bytes 3 and 4 of the magic (\r\n) might not
282 be read as they are on disk. */
283 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
284 unsigned char buf[2];
285 /* Mess: In case of -x, the stream is NOT at its start now,
286 and ungetc() was used to push back the first newline,
287 which makes the current stream position formally undefined,
288 and a x-platform nightmare.
289 Unfortunately, we have no direct way to know whether -x
290 was specified. So we use a terrible hack: if the current
291 stream position is not 0, we assume -x was specified, and
292 give up. Bug 132850 on SourceForge spells out the
293 hopelessness of trying anything else (fseek and ftell
294 don't work predictably x-platform for text-mode files).
295 */
296 int ispyc = 0;
297 if (ftell(fp) == 0) {
298 if (fread(buf, 1, 2, fp) == 2 &&
299 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
300 ispyc = 1;
301 rewind(fp);
302 }
303 return ispyc;
304 }
305 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000306}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000307
Antoine Pitrou32d483c2013-07-30 21:01:23 +0200308static int
309set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000310{
Eric Snow32439d62015-05-02 19:15:18 -0600311 PyObject *filename_obj, *bootstrap, *loader_type = NULL, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +1000312 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200313
314 filename_obj = PyUnicode_DecodeFSDefault(filename);
315 if (filename_obj == NULL)
316 return -1;
Victor Stinner81a7be32020-04-14 15:14:01 +0200317 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600318 bootstrap = PyObject_GetAttrString(interp->importlib,
319 "_bootstrap_external");
320 if (bootstrap != NULL) {
321 loader_type = PyObject_GetAttrString(bootstrap, loader_name);
322 Py_DECREF(bootstrap);
323 }
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000324 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200325 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000326 return -1;
327 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200328 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000329 Py_DECREF(loader_type);
330 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000331 return -1;
332 }
Nick Coghlanb7a58942012-07-15 23:21:08 +1000333 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
334 result = -1;
335 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000336 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000337 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +1000338}
339
340int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000341PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 PyObject *m, *d, *v;
345 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100346 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000347 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 m = PyImport_AddModule("__main__");
350 if (m == NULL)
351 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100352 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 d = PyModule_GetDict(m);
354 if (PyDict_GetItemString(d, "__file__") == NULL) {
355 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000356 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100358 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (PyDict_SetItemString(d, "__file__", f) < 0) {
360 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100361 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 }
Barry Warsaw916048d2011-09-20 14:45:44 -0400363 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
364 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100365 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -0400366 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 set_file_name = 1;
368 Py_DECREF(f);
369 }
370 len = strlen(filename);
371 ext = filename + len - (len > 4 ? 4 : 0);
372 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +0200373 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 /* Try to run a pyc file. First, re-open in binary */
375 if (closeit)
376 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200377 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 goto done;
380 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000381
382 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
383 fprintf(stderr, "python: failed to set __main__.__loader__\n");
384 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +0200385 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +1000386 goto done;
387 }
Christian Heimes04ac4c12012-09-11 15:47:28 +0200388 v = run_pyc_file(pyc_fp, filename, d, d, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000390 /* When running from stdin, leave __main__.__loader__ alone */
391 if (strcmp(filename, "<stdin>") != 0 &&
392 set_main_loader(d, filename, "SourceFileLoader") < 0) {
393 fprintf(stderr, "python: failed to set __main__.__loader__\n");
394 ret = -1;
395 goto done;
396 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
398 closeit, flags);
399 }
400 flush_io();
401 if (v == NULL) {
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600402 Py_CLEAR(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 goto done;
405 }
406 Py_DECREF(v);
407 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000408 done:
INADA Naoki82daa602018-11-29 20:01:27 +0900409 if (set_file_name) {
410 if (PyDict_DelItemString(d, "__file__")) {
411 PyErr_Clear();
412 }
413 if (PyDict_DelItemString(d, "__cached__")) {
414 PyErr_Clear();
415 }
416 }
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600417 Py_XDECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000419}
420
421int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000422PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 PyObject *m, *d, *v;
425 m = PyImport_AddModule("__main__");
426 if (m == NULL)
427 return -1;
428 d = PyModule_GetDict(m);
429 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
430 if (v == NULL) {
431 PyErr_Print();
432 return -1;
433 }
434 Py_DECREF(v);
435 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000436}
437
Barry Warsaw035574d1997-08-29 22:07:17 +0000438static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100439parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
Ammar Askar90d29702020-06-02 08:17:24 +0000440 Py_ssize_t *lineno, Py_ssize_t *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000441{
Ammar Askar90d29702020-06-02 08:17:24 +0000442 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200444 _Py_IDENTIFIER(msg);
445 _Py_IDENTIFIER(filename);
446 _Py_IDENTIFIER(lineno);
447 _Py_IDENTIFIER(offset);
448 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000449
Benjamin Peterson80d50422012-04-03 00:30:38 -0400450 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100451 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400454 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400455 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000457
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400458 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400459 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400461 if (v == Py_None) {
462 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100463 *filename = _PyUnicode_FromId(&PyId_string);
464 if (*filename == NULL)
465 goto finally;
466 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400467 }
468 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100469 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400470 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000471
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400472 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400473 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000475 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (hold < 0 && PyErr_Occurred())
478 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300479 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000480
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400481 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400482 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 goto finally;
484 if (v == Py_None) {
485 *offset = -1;
486 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000488 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (hold < 0 && PyErr_Occurred())
491 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300492 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000494
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400495 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400496 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400498 if (v == Py_None) {
499 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400501 }
502 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100503 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400504 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000506
507finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400508 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100509 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000511}
512
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000513static void
Ammar Askar90d29702020-06-02 08:17:24 +0000514print_error_text(PyObject *f, Py_ssize_t offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000515{
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700516 /* Convert text to a char pointer; return if error */
517 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100518 if (text == NULL)
519 return;
520
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700521 /* Convert offset from 1-based to 0-based */
522 offset--;
523
524 /* Strip leading whitespace from text, adjusting offset as we go */
525 while (*text == ' ' || *text == '\t' || *text == '\f') {
526 text++;
527 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700529
530 /* Calculate text length excluding trailing newline */
531 Py_ssize_t len = strlen(text);
532 if (len > 0 && text[len-1] == '\n') {
533 len--;
534 }
535
536 /* Clip offset to at most len */
537 if (offset > len) {
538 offset = len;
539 }
540
541 /* Skip past newlines embedded in text */
542 for (;;) {
543 const char *nl = strchr(text, '\n');
544 if (nl == NULL) {
545 break;
546 }
547 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000548 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700549 break;
550 }
551 inl += 1;
552 text += inl;
553 len -= inl;
554 offset -= (int)inl;
555 }
556
557 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 PyFile_WriteString(" ", f);
559 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700560
561 /* Make sure there's a newline at the end */
562 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700564 }
565
566 /* Don't print caret if it points to the left of the text */
567 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700569
570 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700572 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700574 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000576}
577
Tim Peterscf615b52003-04-19 18:47:02 +0000578
Victor Stinner12083282019-05-17 23:05:29 +0200579int
580_Py_HandleSystemExit(int *exitcode_p)
581{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200582 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200583 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 /* Don't exit if -i flag was given. This flag is set to 0
585 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200586 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200587 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000588
Victor Stinner12083282019-05-17 23:05:29 +0200589 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
590 return 0;
591 }
592
593 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200597
598 int exitcode = 0;
599 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200601 }
602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (PyExceptionInstance_Check(value)) {
604 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200605 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200606 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (code) {
608 Py_DECREF(value);
609 value = code;
610 if (value == Py_None)
611 goto done;
612 }
613 /* If we failed to dig out the 'code' attribute,
614 just let the else clause below print the error. */
615 }
Victor Stinner12083282019-05-17 23:05:29 +0200616
617 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200619 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100621 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000622 /* We clear the exception here to avoid triggering the assertion
623 * in PyObject_Str that ensures it won't silently lose exception
624 * details.
625 */
626 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000627 if (sys_stderr != NULL && sys_stderr != Py_None) {
628 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
629 } else {
630 PyObject_Print(value, stderr, Py_PRINT_RAW);
631 fflush(stderr);
632 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 PySys_WriteStderr("\n");
634 exitcode = 1;
635 }
Victor Stinner12083282019-05-17 23:05:29 +0200636
Tim Peterscf615b52003-04-19 18:47:02 +0000637 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 /* Restore and clear the exception info, in order to properly decref
639 * the exception, value, and traceback. If we just exit instead,
640 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
641 * some finalizers from running.
642 */
643 PyErr_Restore(exception, value, tb);
644 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200645 *exitcode_p = exitcode;
646 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000647}
648
Victor Stinner12083282019-05-17 23:05:29 +0200649
650static void
651handle_system_exit(void)
652{
653 int exitcode;
654 if (_Py_HandleSystemExit(&exitcode)) {
655 Py_Exit(exitcode);
656 }
657}
658
659
Victor Stinner438a12d2019-05-24 17:01:38 +0200660static void
661_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000664
Victor Stinner12083282019-05-17 23:05:29 +0200665 handle_system_exit();
666
Victor Stinner438a12d2019-05-24 17:01:38 +0200667 _PyErr_Fetch(tstate, &exception, &v, &tb);
668 if (exception == NULL) {
669 goto done;
670 }
671
672 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 if (tb == NULL) {
674 tb = Py_None;
675 Py_INCREF(tb);
676 }
677 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200678 if (exception == NULL) {
679 goto done;
680 }
681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 /* Now we know v != NULL too */
683 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200684 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200685 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200686 }
687 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200688 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200689 }
690 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200691 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 }
Victor Stinner09054372013-11-06 22:41:44 +0100694 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100695 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
696 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800697 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
698 PyErr_Clear();
699 goto done;
700 }
701 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
702 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200704 PyObject* stack[3];
705 PyObject *result;
706
707 stack[0] = exception;
708 stack[1] = v;
709 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200710 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200712 handle_system_exit();
713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200715 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
716 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 /* It should not be possible for exception2 or v2
718 to be NULL. However PyErr_Display() can't
719 tolerate NULLs, so just be safe. */
720 if (exception2 == NULL) {
721 exception2 = Py_None;
722 Py_INCREF(exception2);
723 }
724 if (v2 == NULL) {
725 v2 = Py_None;
726 Py_INCREF(v2);
727 }
728 fflush(stdout);
729 PySys_WriteStderr("Error in sys.excepthook:\n");
730 PyErr_Display(exception2, v2, tb2);
731 PySys_WriteStderr("\nOriginal exception was:\n");
732 PyErr_Display(exception, v, tb);
733 Py_DECREF(exception2);
734 Py_DECREF(v2);
735 Py_XDECREF(tb2);
736 }
737 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200738 }
739 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PySys_WriteStderr("sys.excepthook is missing\n");
741 PyErr_Display(exception, v, tb);
742 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200743
744done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 Py_XDECREF(exception);
746 Py_XDECREF(v);
747 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000748}
749
Victor Stinner438a12d2019-05-24 17:01:38 +0200750void
751_PyErr_Print(PyThreadState *tstate)
752{
753 _PyErr_PrintEx(tstate, 1);
754}
755
756void
757PyErr_PrintEx(int set_sys_last_vars)
758{
759 PyThreadState *tstate = _PyThreadState_GET();
760 _PyErr_PrintEx(tstate, set_sys_last_vars);
761}
762
763void
764PyErr_Print(void)
765{
766 PyErr_PrintEx(1);
767}
768
Benjamin Petersone6528212008-07-15 15:32:09 +0000769static void
770print_exception(PyObject *f, PyObject *value)
771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 int err = 0;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300773 PyObject *type, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200774 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100777 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
778 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
779 err += PyFile_WriteString(" found\n", f);
780 if (err)
781 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 return;
783 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 Py_INCREF(value);
786 fflush(stdout);
787 type = (PyObject *) Py_TYPE(value);
788 tb = PyException_GetTraceback(value);
789 if (tb && tb != Py_None)
790 err = PyTraceBack_Print(tb, f);
791 if (err == 0 &&
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300792 (err = _PyObject_LookupAttrId(value, &PyId_print_file_and_line, &tmp)) > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100794 PyObject *message, *filename, *text;
Ammar Askar90d29702020-06-02 08:17:24 +0000795 Py_ssize_t lineno, offset;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300796 err = 0;
797 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 if (!parse_syntax_error(value, &message, &filename,
799 &lineno, &offset, &text))
800 PyErr_Clear();
801 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100802 PyObject *line;
803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 Py_DECREF(value);
805 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100806
Ammar Askar90d29702020-06-02 08:17:24 +0000807 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100808 filename, lineno);
809 Py_DECREF(filename);
810 if (line != NULL) {
811 PyFile_WriteObject(line, f, Py_PRINT_RAW);
812 Py_DECREF(line);
813 }
814
815 if (text != NULL) {
816 print_error_text(f, offset, text);
817 Py_DECREF(text);
818 }
819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 /* Can't be bothered to check all those
821 PyFile_WriteString() calls */
822 if (PyErr_Occurred())
823 err = -1;
824 }
825 }
826 if (err) {
827 /* Don't do anything else */
828 }
829 else {
830 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300831 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200832 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 assert(PyExceptionClass_Check(type));
834 className = PyExceptionClass_Name(type);
835 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300836 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (dot != NULL)
838 className = dot+1;
839 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000840
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200841 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 if (moduleName == NULL || !PyUnicode_Check(moduleName))
843 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200844 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 err = PyFile_WriteString("<unknown>", f);
846 }
847 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200848 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 {
Victor Stinner937114f2013-11-07 00:12:30 +0100850 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 err += PyFile_WriteString(".", f);
852 }
853 Py_DECREF(moduleName);
854 }
855 if (err == 0) {
856 if (className == NULL)
857 err = PyFile_WriteString("<unknown>", f);
858 else
859 err = PyFile_WriteString(className, f);
860 }
861 }
862 if (err == 0 && (value != Py_None)) {
863 PyObject *s = PyObject_Str(value);
864 /* only print colon if the str() of the
865 object is not the empty string
866 */
Martin Panter3263f682016-02-28 03:16:11 +0000867 if (s == NULL) {
868 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000870 PyFile_WriteString(": <exception str() failed>", f);
871 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100873 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 err = PyFile_WriteString(": ", f);
875 if (err == 0)
876 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
877 Py_XDECREF(s);
878 }
879 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000880 if (err < 0) {
881 PyErr_Clear();
882 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 err += PyFile_WriteString("\n", f);
884 Py_XDECREF(tb);
885 Py_DECREF(value);
886 /* If an error happened here, don't show it.
887 XXX This is wrong, but too many callers rely on this behavior. */
888 if (err != 0)
889 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000890}
891
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200892static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 "\nThe above exception was the direct cause "
894 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000895
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200896static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 "\nDuring handling of the above exception, "
898 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000899
900static void
901print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 int err = 0, res;
904 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (seen != NULL) {
907 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400908 PyObject *value_id = PyLong_FromVoidPtr(value);
909 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyErr_Clear();
911 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400912 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 cause = PyException_GetCause(value);
914 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700915 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -0400916 check_id = PyLong_FromVoidPtr(cause);
917 if (check_id == NULL) {
918 res = -1;
919 } else {
920 res = PySet_Contains(seen, check_id);
921 Py_DECREF(check_id);
922 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 if (res == -1)
924 PyErr_Clear();
925 if (res == 0) {
926 print_exception_recursive(
927 f, cause, seen);
928 err |= PyFile_WriteString(
929 cause_message, f);
930 }
931 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700932 else if (context &&
933 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -0400934 check_id = PyLong_FromVoidPtr(context);
935 if (check_id == NULL) {
936 res = -1;
937 } else {
938 res = PySet_Contains(seen, check_id);
939 Py_DECREF(check_id);
940 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (res == -1)
942 PyErr_Clear();
943 if (res == 0) {
944 print_exception_recursive(
945 f, context, seen);
946 err |= PyFile_WriteString(
947 context_message, f);
948 }
949 }
950 Py_XDECREF(context);
951 Py_XDECREF(cause);
952 }
Zane Bitterde860732017-10-17 17:29:39 -0400953 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 }
955 print_exception(f, value);
956 if (err != 0)
957 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000958}
959
Thomas Wouters477c8d52006-05-27 19:21:47 +0000960void
Victor Stinnercd590a72019-05-28 00:39:52 +0200961_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000962{
Victor Stinnercd590a72019-05-28 00:39:52 +0200963 assert(file != NULL && file != Py_None);
964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +0200966 if (PyExceptionInstance_Check(value)
967 && tb != NULL && PyTraceBack_Check(tb)) {
968 /* Put the traceback on the exception, otherwise it won't get
969 displayed. See issue #18776. */
970 PyObject *cur_tb = PyException_GetTraceback(value);
971 if (cur_tb == NULL)
972 PyException_SetTraceback(value, tb);
973 else
974 Py_DECREF(cur_tb);
975 }
Victor Stinnercd590a72019-05-28 00:39:52 +0200976
977 /* We choose to ignore seen being possibly NULL, and report
978 at least the main exception (it could be a MemoryError).
979 */
980 seen = PySet_New(NULL);
981 if (seen == NULL) {
982 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 }
Victor Stinnercd590a72019-05-28 00:39:52 +0200984 print_exception_recursive(file, value, seen);
985 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +0200986
987 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200988 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +0200989 if (!res) {
990 /* Silently ignore file.flush() error */
991 PyErr_Clear();
992 }
993 else {
994 Py_DECREF(res);
995 }
Victor Stinnercd590a72019-05-28 00:39:52 +0200996}
997
998void
999PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1000{
1001 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1002 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 _PyObject_Dump(value);
1004 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001005 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001007 if (file == Py_None) {
1008 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001010
1011 _PyErr_Display(file, exception, value, tb);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001012}
1013
Guido van Rossum82598051997-03-05 00:20:32 +00001014PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001015PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 PyObject *ret = NULL;
1019 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001020 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001021 PyObject *filename;
1022
1023 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1024 if (filename == NULL)
1025 return NULL;
1026
1027 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (arena == NULL)
1029 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001030
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001031 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001034 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyArena_Free(arena);
1036 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001037}
1038
1039PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001040PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001042{
Victor Stinner95701bd2013-11-06 18:41:07 +01001043 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001045 PyArena *arena = NULL;
1046 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001047
Victor Stinner95701bd2013-11-06 18:41:07 +01001048 filename = PyUnicode_DecodeFSDefault(filename_str);
1049 if (filename == NULL)
1050 goto exit;
1051
1052 arena = PyArena_New();
1053 if (arena == NULL)
1054 goto exit;
1055
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001056 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, NULL, NULL,
1057 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (closeit)
1060 fclose(fp);
1061 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001062 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 }
1064 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01001065
1066exit:
1067 Py_XDECREF(filename);
1068 if (arena != NULL)
1069 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001071}
1072
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001073static void
1074flush_io(void)
1075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PyObject *f, *r;
1077 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 /* Save the current exception */
1080 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001081
Victor Stinnerbd303c12013-11-07 23:07:29 +01001082 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001084 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 if (r)
1086 Py_DECREF(r);
1087 else
1088 PyErr_Clear();
1089 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001090 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001092 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (r)
1094 Py_DECREF(r);
1095 else
1096 PyErr_Clear();
1097 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001100}
1101
Guido van Rossum82598051997-03-05 00:20:32 +00001102static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001103run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001104{
1105 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001106 /*
1107 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1108 * _just in case_ someone is calling into an embedded Python where they
1109 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1110 * leave config.install_signal_handlers set to 0?!?) but then later call
1111 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1112 * its interpreter exits). We don't want a previous embedded interpreter's
1113 * uncaught exception to trigger an unexplained signal exit from a future
1114 * Py_Main() based one.
1115 */
1116 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001117
1118 /* Set globals['__builtins__'] if it doesn't exist */
1119 if (globals != NULL && PyDict_GetItemString(globals, "__builtins__") == NULL) {
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001120 if (PyDict_SetItemString(globals, "__builtins__",
1121 tstate->interp->builtins) < 0) {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001122 return NULL;
1123 }
1124 }
1125
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001126 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001127 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001128 _Py_UnhandledKeyboardInterrupt = 1;
1129 }
1130 return v;
1131}
1132
1133static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001134run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1135 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001136{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001137 PyThreadState *tstate = _PyThreadState_GET();
1138 PyCodeObject *co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 if (co == NULL)
1140 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001141
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001142 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001143 Py_DECREF(co);
1144 return NULL;
1145 }
1146
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001147 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 Py_DECREF(co);
1149 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001150}
1151
Guido van Rossum82598051997-03-05 00:20:32 +00001152static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001153run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001155{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001156 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 PyCodeObject *co;
1158 PyObject *v;
1159 long magic;
1160 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 magic = PyMarshal_ReadLongFromFile(fp);
1163 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001164 if (!PyErr_Occurred())
1165 PyErr_SetString(PyExc_RuntimeError,
1166 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001167 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001169 /* Skip the rest of the header. */
1170 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001171 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001173 if (PyErr_Occurred()) {
1174 goto error;
1175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (v == NULL || !PyCode_Check(v)) {
1178 Py_XDECREF(v);
1179 PyErr_SetString(PyExc_RuntimeError,
1180 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001181 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 }
Zackery Spytzea737752018-06-23 21:15:24 -06001183 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001185 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (v && flags)
1187 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1188 Py_DECREF(co);
1189 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001190error:
1191 fclose(fp);
1192 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001193}
1194
Guido van Rossum82598051997-03-05 00:20:32 +00001195PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001196Py_CompileStringObject(const char *str, PyObject *filename, int start,
1197 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyCodeObject *co;
1200 mod_ty mod;
1201 PyArena *arena = PyArena_New();
1202 if (arena == NULL)
1203 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001204
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001205 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (mod == NULL) {
1207 PyArena_Free(arena);
1208 return NULL;
1209 }
1210 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1211 PyObject *result = PyAST_mod2obj(mod);
1212 PyArena_Free(arena);
1213 return result;
1214 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001215 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyArena_Free(arena);
1217 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001218}
1219
Victor Stinner14e461d2013-08-26 22:28:21 +02001220PyObject *
1221Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1222 PyCompilerFlags *flags, int optimize)
1223{
1224 PyObject *filename, *co;
1225 filename = PyUnicode_DecodeFSDefault(filename_str);
1226 if (filename == NULL)
1227 return NULL;
1228 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1229 Py_DECREF(filename);
1230 return co;
1231}
1232
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001233/* For use in Py_LIMITED_API */
1234#undef Py_CompileString
1235PyObject *
1236PyCompileString(const char *str, const char *filename, int start)
1237{
1238 return Py_CompileStringFlags(str, filename, start, NULL);
1239}
1240
Dino Viehland41540692019-05-28 16:21:17 -07001241const char *
1242_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1243{
1244 const char *str;
1245 Py_ssize_t size;
1246 Py_buffer view;
1247
1248 *cmd_copy = NULL;
1249 if (PyUnicode_Check(cmd)) {
1250 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1251 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1252 if (str == NULL)
1253 return NULL;
1254 }
1255 else if (PyBytes_Check(cmd)) {
1256 str = PyBytes_AS_STRING(cmd);
1257 size = PyBytes_GET_SIZE(cmd);
1258 }
1259 else if (PyByteArray_Check(cmd)) {
1260 str = PyByteArray_AS_STRING(cmd);
1261 size = PyByteArray_GET_SIZE(cmd);
1262 }
1263 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1264 /* Copy to NUL-terminated buffer. */
1265 *cmd_copy = PyBytes_FromStringAndSize(
1266 (const char *)view.buf, view.len);
1267 PyBuffer_Release(&view);
1268 if (*cmd_copy == NULL) {
1269 return NULL;
1270 }
1271 str = PyBytes_AS_STRING(*cmd_copy);
1272 size = PyBytes_GET_SIZE(*cmd_copy);
1273 }
1274 else {
1275 PyErr_Format(PyExc_TypeError,
1276 "%s() arg 1 must be a %s object",
1277 funcname, what);
1278 return NULL;
1279 }
1280
1281 if (strlen(str) != (size_t)size) {
1282 PyErr_SetString(PyExc_ValueError,
1283 "source code string cannot contain null bytes");
1284 Py_CLEAR(*cmd_copy);
1285 return NULL;
1286 }
1287 return str;
1288}
1289
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001290struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02001291Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001292{
Victor Stinner37d66d72019-06-13 02:16:41 +02001293 PyCompilerFlags flags = _PyCompilerFlags_INIT;
Dino Viehland41540692019-05-28 16:21:17 -07001294 return _Py_SymtableStringObjectFlags(str, filename, start, &flags);
1295}
1296
1297struct symtable *
1298_Py_SymtableStringObjectFlags(const char *str, PyObject *filename, int start, PyCompilerFlags *flags)
1299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 struct symtable *st;
1301 mod_ty mod;
Victor Stinner14e461d2013-08-26 22:28:21 +02001302 PyArena *arena;
1303
1304 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (arena == NULL)
1306 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001307
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001308 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (mod == NULL) {
1310 PyArena_Free(arena);
1311 return NULL;
1312 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001313 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 PyArena_Free(arena);
1315 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001316}
1317
Victor Stinner14e461d2013-08-26 22:28:21 +02001318struct symtable *
1319Py_SymtableString(const char *str, const char *filename_str, int start)
1320{
1321 PyObject *filename;
1322 struct symtable *st;
1323
1324 filename = PyUnicode_DecodeFSDefault(filename_str);
1325 if (filename == NULL)
1326 return NULL;
1327 st = Py_SymtableStringObject(str, filename, start);
1328 Py_DECREF(filename);
1329 return st;
1330}
1331
Zachary Warec4821d62014-11-21 23:35:12 -06001332#if defined(USE_STACKCHECK)
1333#if defined(WIN32) && defined(_MSC_VER)
1334
1335/* Stack checking for Microsoft C */
1336
1337#include <malloc.h>
1338#include <excpt.h>
1339
1340/*
1341 * Return non-zero when we run out of memory on the stack; zero otherwise.
1342 */
1343int
1344PyOS_CheckStack(void)
1345{
1346 __try {
1347 /* alloca throws a stack overflow exception if there's
1348 not enough space left on the stack */
1349 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1350 return 0;
1351 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1352 EXCEPTION_EXECUTE_HANDLER :
1353 EXCEPTION_CONTINUE_SEARCH) {
1354 int errcode = _resetstkoflw();
1355 if (errcode == 0)
1356 {
1357 Py_FatalError("Could not reset the stack!");
1358 }
1359 }
1360 return 1;
1361}
1362
1363#endif /* WIN32 && _MSC_VER */
1364
1365/* Alternate implementations can be added here... */
1366
1367#endif /* USE_STACKCHECK */
1368
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001369#ifdef __cplusplus
1370}
1371#endif