blob: ff80103050e4e2cff35daaa7738c5ec3c9ca73b9 [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;
773 PyObject *type, *tb;
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 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200792 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
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;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (!parse_syntax_error(value, &message, &filename,
797 &lineno, &offset, &text))
798 PyErr_Clear();
799 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100800 PyObject *line;
801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 Py_DECREF(value);
803 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100804
Ammar Askar90d29702020-06-02 08:17:24 +0000805 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100806 filename, lineno);
807 Py_DECREF(filename);
808 if (line != NULL) {
809 PyFile_WriteObject(line, f, Py_PRINT_RAW);
810 Py_DECREF(line);
811 }
812
813 if (text != NULL) {
814 print_error_text(f, offset, text);
815 Py_DECREF(text);
816 }
817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 /* Can't be bothered to check all those
819 PyFile_WriteString() calls */
820 if (PyErr_Occurred())
821 err = -1;
822 }
823 }
824 if (err) {
825 /* Don't do anything else */
826 }
827 else {
828 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300829 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200830 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 assert(PyExceptionClass_Check(type));
832 className = PyExceptionClass_Name(type);
833 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300834 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (dot != NULL)
836 className = dot+1;
837 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000838
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200839 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (moduleName == NULL || !PyUnicode_Check(moduleName))
841 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200842 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 err = PyFile_WriteString("<unknown>", f);
844 }
845 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200846 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 {
Victor Stinner937114f2013-11-07 00:12:30 +0100848 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 err += PyFile_WriteString(".", f);
850 }
851 Py_DECREF(moduleName);
852 }
853 if (err == 0) {
854 if (className == NULL)
855 err = PyFile_WriteString("<unknown>", f);
856 else
857 err = PyFile_WriteString(className, f);
858 }
859 }
860 if (err == 0 && (value != Py_None)) {
861 PyObject *s = PyObject_Str(value);
862 /* only print colon if the str() of the
863 object is not the empty string
864 */
Martin Panter3263f682016-02-28 03:16:11 +0000865 if (s == NULL) {
866 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000868 PyFile_WriteString(": <exception str() failed>", f);
869 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100871 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 err = PyFile_WriteString(": ", f);
873 if (err == 0)
874 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
875 Py_XDECREF(s);
876 }
877 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000878 if (err < 0) {
879 PyErr_Clear();
880 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 err += PyFile_WriteString("\n", f);
882 Py_XDECREF(tb);
883 Py_DECREF(value);
884 /* If an error happened here, don't show it.
885 XXX This is wrong, but too many callers rely on this behavior. */
886 if (err != 0)
887 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000888}
889
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200890static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 "\nThe above exception was the direct cause "
892 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000893
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200894static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 "\nDuring handling of the above exception, "
896 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000897
898static void
899print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 int err = 0, res;
902 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (seen != NULL) {
905 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400906 PyObject *value_id = PyLong_FromVoidPtr(value);
907 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 PyErr_Clear();
909 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400910 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 cause = PyException_GetCause(value);
912 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700913 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -0400914 check_id = PyLong_FromVoidPtr(cause);
915 if (check_id == NULL) {
916 res = -1;
917 } else {
918 res = PySet_Contains(seen, check_id);
919 Py_DECREF(check_id);
920 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (res == -1)
922 PyErr_Clear();
923 if (res == 0) {
924 print_exception_recursive(
925 f, cause, seen);
926 err |= PyFile_WriteString(
927 cause_message, f);
928 }
929 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700930 else if (context &&
931 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -0400932 check_id = PyLong_FromVoidPtr(context);
933 if (check_id == NULL) {
934 res = -1;
935 } else {
936 res = PySet_Contains(seen, check_id);
937 Py_DECREF(check_id);
938 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (res == -1)
940 PyErr_Clear();
941 if (res == 0) {
942 print_exception_recursive(
943 f, context, seen);
944 err |= PyFile_WriteString(
945 context_message, f);
946 }
947 }
948 Py_XDECREF(context);
949 Py_XDECREF(cause);
950 }
Zane Bitterde860732017-10-17 17:29:39 -0400951 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 }
953 print_exception(f, value);
954 if (err != 0)
955 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000956}
957
Thomas Wouters477c8d52006-05-27 19:21:47 +0000958void
Victor Stinnercd590a72019-05-28 00:39:52 +0200959_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000960{
Victor Stinnercd590a72019-05-28 00:39:52 +0200961 assert(file != NULL && file != Py_None);
962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +0200964 if (PyExceptionInstance_Check(value)
965 && tb != NULL && PyTraceBack_Check(tb)) {
966 /* Put the traceback on the exception, otherwise it won't get
967 displayed. See issue #18776. */
968 PyObject *cur_tb = PyException_GetTraceback(value);
969 if (cur_tb == NULL)
970 PyException_SetTraceback(value, tb);
971 else
972 Py_DECREF(cur_tb);
973 }
Victor Stinnercd590a72019-05-28 00:39:52 +0200974
975 /* We choose to ignore seen being possibly NULL, and report
976 at least the main exception (it could be a MemoryError).
977 */
978 seen = PySet_New(NULL);
979 if (seen == NULL) {
980 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 }
Victor Stinnercd590a72019-05-28 00:39:52 +0200982 print_exception_recursive(file, value, seen);
983 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +0200984
985 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200986 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +0200987 if (!res) {
988 /* Silently ignore file.flush() error */
989 PyErr_Clear();
990 }
991 else {
992 Py_DECREF(res);
993 }
Victor Stinnercd590a72019-05-28 00:39:52 +0200994}
995
996void
997PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
998{
999 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1000 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 _PyObject_Dump(value);
1002 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001003 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001005 if (file == Py_None) {
1006 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001008
1009 _PyErr_Display(file, exception, value, tb);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001010}
1011
Guido van Rossum82598051997-03-05 00:20:32 +00001012PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001013PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 PyObject *ret = NULL;
1017 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001018 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001019 PyObject *filename;
1020
1021 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1022 if (filename == NULL)
1023 return NULL;
1024
1025 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 if (arena == NULL)
1027 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001028
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001029 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001032 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 PyArena_Free(arena);
1034 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001035}
1036
1037PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001038PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001040{
Victor Stinner95701bd2013-11-06 18:41:07 +01001041 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001043 PyArena *arena = NULL;
1044 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001045
Victor Stinner95701bd2013-11-06 18:41:07 +01001046 filename = PyUnicode_DecodeFSDefault(filename_str);
1047 if (filename == NULL)
1048 goto exit;
1049
1050 arena = PyArena_New();
1051 if (arena == NULL)
1052 goto exit;
1053
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001054 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, NULL, NULL,
1055 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (closeit)
1058 fclose(fp);
1059 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001060 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 }
1062 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01001063
1064exit:
1065 Py_XDECREF(filename);
1066 if (arena != NULL)
1067 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001069}
1070
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001071static void
1072flush_io(void)
1073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 PyObject *f, *r;
1075 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 /* Save the current exception */
1078 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001079
Victor Stinnerbd303c12013-11-07 23:07:29 +01001080 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001082 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 if (r)
1084 Py_DECREF(r);
1085 else
1086 PyErr_Clear();
1087 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001088 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001090 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (r)
1092 Py_DECREF(r);
1093 else
1094 PyErr_Clear();
1095 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001098}
1099
Guido van Rossum82598051997-03-05 00:20:32 +00001100static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001101run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001102{
1103 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001104 /*
1105 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1106 * _just in case_ someone is calling into an embedded Python where they
1107 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1108 * leave config.install_signal_handlers set to 0?!?) but then later call
1109 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1110 * its interpreter exits). We don't want a previous embedded interpreter's
1111 * uncaught exception to trigger an unexplained signal exit from a future
1112 * Py_Main() based one.
1113 */
1114 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001115
1116 /* Set globals['__builtins__'] if it doesn't exist */
1117 if (globals != NULL && PyDict_GetItemString(globals, "__builtins__") == NULL) {
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001118 if (PyDict_SetItemString(globals, "__builtins__",
1119 tstate->interp->builtins) < 0) {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001120 return NULL;
1121 }
1122 }
1123
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001124 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001125 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001126 _Py_UnhandledKeyboardInterrupt = 1;
1127 }
1128 return v;
1129}
1130
1131static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001132run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1133 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001134{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001135 PyThreadState *tstate = _PyThreadState_GET();
1136 PyCodeObject *co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (co == NULL)
1138 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001139
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001140 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001141 Py_DECREF(co);
1142 return NULL;
1143 }
1144
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001145 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 Py_DECREF(co);
1147 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001148}
1149
Guido van Rossum82598051997-03-05 00:20:32 +00001150static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001151run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001153{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001154 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyCodeObject *co;
1156 PyObject *v;
1157 long magic;
1158 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 magic = PyMarshal_ReadLongFromFile(fp);
1161 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001162 if (!PyErr_Occurred())
1163 PyErr_SetString(PyExc_RuntimeError,
1164 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001165 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001167 /* Skip the rest of the header. */
1168 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001169 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001171 if (PyErr_Occurred()) {
1172 goto error;
1173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (v == NULL || !PyCode_Check(v)) {
1176 Py_XDECREF(v);
1177 PyErr_SetString(PyExc_RuntimeError,
1178 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001179 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 }
Zackery Spytzea737752018-06-23 21:15:24 -06001181 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001183 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (v && flags)
1185 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1186 Py_DECREF(co);
1187 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001188error:
1189 fclose(fp);
1190 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001191}
1192
Guido van Rossum82598051997-03-05 00:20:32 +00001193PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001194Py_CompileStringObject(const char *str, PyObject *filename, int start,
1195 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyCodeObject *co;
1198 mod_ty mod;
1199 PyArena *arena = PyArena_New();
1200 if (arena == NULL)
1201 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001202
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001203 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (mod == NULL) {
1205 PyArena_Free(arena);
1206 return NULL;
1207 }
1208 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1209 PyObject *result = PyAST_mod2obj(mod);
1210 PyArena_Free(arena);
1211 return result;
1212 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001213 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 PyArena_Free(arena);
1215 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001216}
1217
Victor Stinner14e461d2013-08-26 22:28:21 +02001218PyObject *
1219Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1220 PyCompilerFlags *flags, int optimize)
1221{
1222 PyObject *filename, *co;
1223 filename = PyUnicode_DecodeFSDefault(filename_str);
1224 if (filename == NULL)
1225 return NULL;
1226 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1227 Py_DECREF(filename);
1228 return co;
1229}
1230
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001231/* For use in Py_LIMITED_API */
1232#undef Py_CompileString
1233PyObject *
1234PyCompileString(const char *str, const char *filename, int start)
1235{
1236 return Py_CompileStringFlags(str, filename, start, NULL);
1237}
1238
Dino Viehland41540692019-05-28 16:21:17 -07001239const char *
1240_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1241{
1242 const char *str;
1243 Py_ssize_t size;
1244 Py_buffer view;
1245
1246 *cmd_copy = NULL;
1247 if (PyUnicode_Check(cmd)) {
1248 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1249 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1250 if (str == NULL)
1251 return NULL;
1252 }
1253 else if (PyBytes_Check(cmd)) {
1254 str = PyBytes_AS_STRING(cmd);
1255 size = PyBytes_GET_SIZE(cmd);
1256 }
1257 else if (PyByteArray_Check(cmd)) {
1258 str = PyByteArray_AS_STRING(cmd);
1259 size = PyByteArray_GET_SIZE(cmd);
1260 }
1261 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1262 /* Copy to NUL-terminated buffer. */
1263 *cmd_copy = PyBytes_FromStringAndSize(
1264 (const char *)view.buf, view.len);
1265 PyBuffer_Release(&view);
1266 if (*cmd_copy == NULL) {
1267 return NULL;
1268 }
1269 str = PyBytes_AS_STRING(*cmd_copy);
1270 size = PyBytes_GET_SIZE(*cmd_copy);
1271 }
1272 else {
1273 PyErr_Format(PyExc_TypeError,
1274 "%s() arg 1 must be a %s object",
1275 funcname, what);
1276 return NULL;
1277 }
1278
1279 if (strlen(str) != (size_t)size) {
1280 PyErr_SetString(PyExc_ValueError,
1281 "source code string cannot contain null bytes");
1282 Py_CLEAR(*cmd_copy);
1283 return NULL;
1284 }
1285 return str;
1286}
1287
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001288struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02001289Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001290{
Victor Stinner37d66d72019-06-13 02:16:41 +02001291 PyCompilerFlags flags = _PyCompilerFlags_INIT;
Dino Viehland41540692019-05-28 16:21:17 -07001292 return _Py_SymtableStringObjectFlags(str, filename, start, &flags);
1293}
1294
1295struct symtable *
1296_Py_SymtableStringObjectFlags(const char *str, PyObject *filename, int start, PyCompilerFlags *flags)
1297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 struct symtable *st;
1299 mod_ty mod;
Victor Stinner14e461d2013-08-26 22:28:21 +02001300 PyArena *arena;
1301
1302 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (arena == NULL)
1304 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001305
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001306 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (mod == NULL) {
1308 PyArena_Free(arena);
1309 return NULL;
1310 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001311 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 PyArena_Free(arena);
1313 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001314}
1315
Victor Stinner14e461d2013-08-26 22:28:21 +02001316struct symtable *
1317Py_SymtableString(const char *str, const char *filename_str, int start)
1318{
1319 PyObject *filename;
1320 struct symtable *st;
1321
1322 filename = PyUnicode_DecodeFSDefault(filename_str);
1323 if (filename == NULL)
1324 return NULL;
1325 st = Py_SymtableStringObject(str, filename, start);
1326 Py_DECREF(filename);
1327 return st;
1328}
1329
Zachary Warec4821d62014-11-21 23:35:12 -06001330#if defined(USE_STACKCHECK)
1331#if defined(WIN32) && defined(_MSC_VER)
1332
1333/* Stack checking for Microsoft C */
1334
1335#include <malloc.h>
1336#include <excpt.h>
1337
1338/*
1339 * Return non-zero when we run out of memory on the stack; zero otherwise.
1340 */
1341int
1342PyOS_CheckStack(void)
1343{
1344 __try {
1345 /* alloca throws a stack overflow exception if there's
1346 not enough space left on the stack */
1347 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1348 return 0;
1349 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1350 EXCEPTION_EXECUTE_HANDLER :
1351 EXCEPTION_CONTINUE_SEARCH) {
1352 int errcode = _resetstkoflw();
1353 if (errcode == 0)
1354 {
1355 Py_FatalError("Could not reset the stack!");
1356 }
1357 }
1358 return 1;
1359}
1360
1361#endif /* WIN32 && _MSC_VER */
1362
1363/* Alternate implementations can be added here... */
1364
1365#endif /* USE_STACKCHECK */
1366
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001367#ifdef __cplusplus
1368}
1369#endif