blob: 7a3b5b52ac417de220bba7c7cd5171f7378e3d4e [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 "node.h" // node
24#include "token.h" // INDENT
25#include "parsetok.h" // perrdetail
26#include "errcode.h" // E_EOF
27#include "code.h" // PyCodeObject
28#include "symtable.h" // PySymtable_BuildObject()
29#include "ast.h" // PyAST_FromNodeObject()
30#include "marshal.h" // PyMarshal_ReadLongFromFile()
31
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030032#include "pegen_interface.h" // PyPegen_ASTFrom*
Pablo Galindoc5fc1562020-04-22 23:29:27 +010033
Victor Stinner4f98f462020-04-15 04:01:58 +020034#ifdef MS_WINDOWS
35# include "malloc.h" // alloca()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000036#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000037
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000038#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020039# undef BYTE
40# include "windows.h"
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000041#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000042
Guido van Rossuma44823b1995-03-14 15:01:17 +000043
Victor Stinnerbd303c12013-11-07 23:07:29 +010044_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010045_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010046_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010048_Py_IDENTIFIER(last_type);
49_Py_IDENTIFIER(last_value);
Victor Stinnerbd303c12013-11-07 23:07:29 +010050_Py_IDENTIFIER(ps1);
51_Py_IDENTIFIER(ps2);
52_Py_IDENTIFIER(stdin);
53_Py_IDENTIFIER(stdout);
54_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010055_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010056
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057#ifdef __cplusplus
58extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000059#endif
60
Guido van Rossumb73cc041993-11-01 16:28:59 +000061/* Forward */
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000062static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010063static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000065static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 PyCompilerFlags *);
xdegayee0582a32017-11-12 16:50:48 +010067static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000068
Guido van Rossum1984f1e1992-08-04 12:41:02 +000069/* Parse input from a file and execute it */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000070int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000071PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +000073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 if (filename == NULL)
75 filename = "???";
76 if (Py_FdIsInteractive(fp, filename)) {
77 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
78 if (closeit)
79 fclose(fp);
80 return err;
81 }
82 else
83 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000084}
85
86int
Victor Stinner95701bd2013-11-06 18:41:07 +010087PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +000088{
Victor Stinner95701bd2013-11-06 18:41:07 +010089 PyObject *filename, *v;
90 int ret, err;
Victor Stinner37d66d72019-06-13 02:16:41 +020091 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
xdegayee0582a32017-11-12 16:50:48 +010092 int nomem_count = 0;
Victor Stinner25420fe2017-11-20 18:12:22 -080093#ifdef Py_REF_DEBUG
Victor Stinnerda7933e2020-04-13 03:04:28 +020094 int show_ref_count = _Py_GetConfig()->show_ref_count;
Victor Stinner25420fe2017-11-20 18:12:22 -080095#endif
Jeremy Hylton9f324e92001-03-01 22:59:14 +000096
Victor Stinner95701bd2013-11-06 18:41:07 +010097 filename = PyUnicode_DecodeFSDefault(filename_str);
98 if (filename == NULL) {
99 PyErr_Print();
100 return -1;
101 }
102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 if (flags == NULL) {
104 flags = &local_flags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
Victor Stinner09054372013-11-06 22:41:44 +0100106 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100108 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_XDECREF(v);
110 }
Victor Stinner09054372013-11-06 22:41:44 +0100111 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100113 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 Py_XDECREF(v);
115 }
xdegayee0582a32017-11-12 16:50:48 +0100116 err = 0;
117 do {
118 ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
119 if (ret == -1 && PyErr_Occurred()) {
120 /* Prevent an endless loop after multiple consecutive MemoryErrors
121 * while still allowing an interactive command to fail with a
122 * MemoryError. */
123 if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
124 if (++nomem_count > 16) {
125 PyErr_Clear();
126 err = -1;
127 break;
128 }
129 } else {
130 nomem_count = 0;
131 }
132 PyErr_Print();
133 flush_io();
134 } else {
135 nomem_count = 0;
136 }
Eric Snowdae02762017-09-14 00:35:58 -0700137#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -0800138 if (show_ref_count) {
Eric Snowdae02762017-09-14 00:35:58 -0700139 _PyDebug_PrintTotalRefs();
Victor Stinner25420fe2017-11-20 18:12:22 -0800140 }
Eric Snowdae02762017-09-14 00:35:58 -0700141#endif
xdegayee0582a32017-11-12 16:50:48 +0100142 } while (ret != E_EOF);
Victor Stinner95701bd2013-11-06 18:41:07 +0100143 Py_DECREF(filename);
144 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000145}
146
xdegayee0582a32017-11-12 16:50:48 +0100147/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
148 * error on failure. */
149static int
150PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
151 PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000152{
Victor Stinner95701bd2013-11-06 18:41:07 +0100153 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 mod_ty mod;
155 PyArena *arena;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200156 const char *ps1 = "", *ps2 = "", *enc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200158 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +0100159 _Py_IDENTIFIER(__main__);
160
161 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
162 if (mod_name == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100163 return -1;
164 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400167 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +0100168 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400169 if (v && v != Py_None) {
170 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
171 if (oenc)
Serhiy Storchaka06515832016-11-20 09:13:07 +0200172 enc = PyUnicode_AsUTF8(oenc);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400173 if (!enc)
174 PyErr_Clear();
175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
Victor Stinner09054372013-11-06 22:41:44 +0100177 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 if (v != NULL) {
179 v = PyObject_Str(v);
180 if (v == NULL)
181 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000182 else if (PyUnicode_Check(v)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200183 ps1 = PyUnicode_AsUTF8(v);
Victor Stinner386fe712010-05-19 00:34:15 +0000184 if (ps1 == NULL) {
185 PyErr_Clear();
186 ps1 = "";
187 }
188 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 }
Victor Stinner09054372013-11-06 22:41:44 +0100190 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (w != NULL) {
192 w = PyObject_Str(w);
193 if (w == NULL)
194 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000195 else if (PyUnicode_Check(w)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200196 ps2 = PyUnicode_AsUTF8(w);
Victor Stinner386fe712010-05-19 00:34:15 +0000197 if (ps2 == NULL) {
198 PyErr_Clear();
199 ps2 = "";
200 }
201 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 }
203 arena = PyArena_New();
204 if (arena == NULL) {
205 Py_XDECREF(v);
206 Py_XDECREF(w);
207 Py_XDECREF(oenc);
208 return -1;
209 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100210
Pablo Galindo1ed83ad2020-06-11 17:30:46 +0100211 mod = PyPegen_ASTFromFileObject(fp, filename, Py_single_input,
212 enc, ps1, ps2, flags, &errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 Py_XDECREF(v);
215 Py_XDECREF(w);
216 Py_XDECREF(oenc);
217 if (mod == NULL) {
218 PyArena_Free(arena);
219 if (errcode == E_EOF) {
220 PyErr_Clear();
221 return E_EOF;
222 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 return -1;
224 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100225 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (m == NULL) {
227 PyArena_Free(arena);
228 return -1;
229 }
230 d = PyModule_GetDict(m);
231 v = run_mod(mod, filename, d, d, flags, arena);
232 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 return -1;
235 }
236 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200237 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000239}
240
Victor Stinner95701bd2013-11-06 18:41:07 +0100241int
xdegayee0582a32017-11-12 16:50:48 +0100242PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
243{
244 int res;
245
246 res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
247 if (res == -1) {
248 PyErr_Print();
249 flush_io();
250 }
251 return res;
252}
253
254int
Victor Stinner95701bd2013-11-06 18:41:07 +0100255PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
256{
257 PyObject *filename;
258 int res;
259
260 filename = PyUnicode_DecodeFSDefault(filename_str);
261 if (filename == NULL) {
262 PyErr_Print();
263 return -1;
264 }
265 res = PyRun_InteractiveOneObject(fp, filename, flags);
266 Py_DECREF(filename);
267 return res;
268}
269
270
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000271/* Check whether a file maybe a pyc file: Look at the extension,
272 the file type, and, if we may close it, at the first few bytes. */
273
274static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000275maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000276{
Brett Cannonf299abd2015-04-13 14:21:02 -0400277 if (strcmp(ext, ".pyc") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 /* Only look into the file if we are allowed to close it, since
281 it then should also be seekable. */
282 if (closeit) {
283 /* Read only two bytes of the magic. If the file was opened in
284 text mode, the bytes 3 and 4 of the magic (\r\n) might not
285 be read as they are on disk. */
286 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
287 unsigned char buf[2];
288 /* Mess: In case of -x, the stream is NOT at its start now,
289 and ungetc() was used to push back the first newline,
290 which makes the current stream position formally undefined,
291 and a x-platform nightmare.
292 Unfortunately, we have no direct way to know whether -x
293 was specified. So we use a terrible hack: if the current
294 stream position is not 0, we assume -x was specified, and
295 give up. Bug 132850 on SourceForge spells out the
296 hopelessness of trying anything else (fseek and ftell
297 don't work predictably x-platform for text-mode files).
298 */
299 int ispyc = 0;
300 if (ftell(fp) == 0) {
301 if (fread(buf, 1, 2, fp) == 2 &&
302 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
303 ispyc = 1;
304 rewind(fp);
305 }
306 return ispyc;
307 }
308 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000309}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000310
Antoine Pitrou32d483c2013-07-30 21:01:23 +0200311static int
312set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000313{
Eric Snow32439d62015-05-02 19:15:18 -0600314 PyObject *filename_obj, *bootstrap, *loader_type = NULL, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +1000315 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200316
317 filename_obj = PyUnicode_DecodeFSDefault(filename);
318 if (filename_obj == NULL)
319 return -1;
Victor Stinner81a7be32020-04-14 15:14:01 +0200320 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600321 bootstrap = PyObject_GetAttrString(interp->importlib,
322 "_bootstrap_external");
323 if (bootstrap != NULL) {
324 loader_type = PyObject_GetAttrString(bootstrap, loader_name);
325 Py_DECREF(bootstrap);
326 }
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000327 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200328 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000329 return -1;
330 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200331 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000332 Py_DECREF(loader_type);
333 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000334 return -1;
335 }
Nick Coghlanb7a58942012-07-15 23:21:08 +1000336 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
337 result = -1;
338 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000339 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000340 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +1000341}
342
343int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000344PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 PyObject *m, *d, *v;
348 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100349 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000350 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 m = PyImport_AddModule("__main__");
353 if (m == NULL)
354 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100355 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 d = PyModule_GetDict(m);
357 if (PyDict_GetItemString(d, "__file__") == NULL) {
358 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000359 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100361 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (PyDict_SetItemString(d, "__file__", f) < 0) {
363 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100364 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 }
Barry Warsaw916048d2011-09-20 14:45:44 -0400366 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
367 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100368 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -0400369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 set_file_name = 1;
371 Py_DECREF(f);
372 }
373 len = strlen(filename);
374 ext = filename + len - (len > 4 ? 4 : 0);
375 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +0200376 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* Try to run a pyc file. First, re-open in binary */
378 if (closeit)
379 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200380 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 goto done;
383 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000384
385 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
386 fprintf(stderr, "python: failed to set __main__.__loader__\n");
387 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +0200388 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +1000389 goto done;
390 }
Christian Heimes04ac4c12012-09-11 15:47:28 +0200391 v = run_pyc_file(pyc_fp, filename, d, d, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000393 /* When running from stdin, leave __main__.__loader__ alone */
394 if (strcmp(filename, "<stdin>") != 0 &&
395 set_main_loader(d, filename, "SourceFileLoader") < 0) {
396 fprintf(stderr, "python: failed to set __main__.__loader__\n");
397 ret = -1;
398 goto done;
399 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
401 closeit, flags);
402 }
403 flush_io();
404 if (v == NULL) {
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600405 Py_CLEAR(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 goto done;
408 }
409 Py_DECREF(v);
410 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000411 done:
INADA Naoki82daa602018-11-29 20:01:27 +0900412 if (set_file_name) {
413 if (PyDict_DelItemString(d, "__file__")) {
414 PyErr_Clear();
415 }
416 if (PyDict_DelItemString(d, "__cached__")) {
417 PyErr_Clear();
418 }
419 }
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600420 Py_XDECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000422}
423
424int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000425PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyObject *m, *d, *v;
428 m = PyImport_AddModule("__main__");
429 if (m == NULL)
430 return -1;
431 d = PyModule_GetDict(m);
432 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
433 if (v == NULL) {
434 PyErr_Print();
435 return -1;
436 }
437 Py_DECREF(v);
438 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000439}
440
Barry Warsaw035574d1997-08-29 22:07:17 +0000441static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100442parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
Ammar Askar90d29702020-06-02 08:17:24 +0000443 Py_ssize_t *lineno, Py_ssize_t *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000444{
Ammar Askar90d29702020-06-02 08:17:24 +0000445 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200447 _Py_IDENTIFIER(msg);
448 _Py_IDENTIFIER(filename);
449 _Py_IDENTIFIER(lineno);
450 _Py_IDENTIFIER(offset);
451 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000452
Benjamin Peterson80d50422012-04-03 00:30:38 -0400453 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100454 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400457 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400458 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000460
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400461 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400462 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400464 if (v == Py_None) {
465 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100466 *filename = _PyUnicode_FromId(&PyId_string);
467 if (*filename == NULL)
468 goto finally;
469 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400470 }
471 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100472 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400473 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000474
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400475 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400476 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000478 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (hold < 0 && PyErr_Occurred())
481 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300482 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000483
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400484 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400485 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 goto finally;
487 if (v == Py_None) {
488 *offset = -1;
489 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000491 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (hold < 0 && PyErr_Occurred())
494 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300495 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000497
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400498 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400499 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400501 if (v == Py_None) {
502 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400504 }
505 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100506 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400507 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000509
510finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400511 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100512 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000514}
515
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000516static void
Ammar Askar90d29702020-06-02 08:17:24 +0000517print_error_text(PyObject *f, Py_ssize_t offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000518{
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700519 /* Convert text to a char pointer; return if error */
520 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100521 if (text == NULL)
522 return;
523
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700524 /* Convert offset from 1-based to 0-based */
525 offset--;
526
527 /* Strip leading whitespace from text, adjusting offset as we go */
528 while (*text == ' ' || *text == '\t' || *text == '\f') {
529 text++;
530 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700532
533 /* Calculate text length excluding trailing newline */
534 Py_ssize_t len = strlen(text);
535 if (len > 0 && text[len-1] == '\n') {
536 len--;
537 }
538
539 /* Clip offset to at most len */
540 if (offset > len) {
541 offset = len;
542 }
543
544 /* Skip past newlines embedded in text */
545 for (;;) {
546 const char *nl = strchr(text, '\n');
547 if (nl == NULL) {
548 break;
549 }
550 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000551 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700552 break;
553 }
554 inl += 1;
555 text += inl;
556 len -= inl;
557 offset -= (int)inl;
558 }
559
560 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 PyFile_WriteString(" ", f);
562 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700563
564 /* Make sure there's a newline at the end */
565 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700567 }
568
569 /* Don't print caret if it points to the left of the text */
570 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700572
573 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700575 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700577 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000579}
580
Tim Peterscf615b52003-04-19 18:47:02 +0000581
Victor Stinner12083282019-05-17 23:05:29 +0200582int
583_Py_HandleSystemExit(int *exitcode_p)
584{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200585 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200586 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 /* Don't exit if -i flag was given. This flag is set to 0
588 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200589 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200590 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000591
Victor Stinner12083282019-05-17 23:05:29 +0200592 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
593 return 0;
594 }
595
596 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200600
601 int exitcode = 0;
602 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200604 }
605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (PyExceptionInstance_Check(value)) {
607 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200608 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200609 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (code) {
611 Py_DECREF(value);
612 value = code;
613 if (value == Py_None)
614 goto done;
615 }
616 /* If we failed to dig out the 'code' attribute,
617 just let the else clause below print the error. */
618 }
Victor Stinner12083282019-05-17 23:05:29 +0200619
620 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200622 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100624 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000625 /* We clear the exception here to avoid triggering the assertion
626 * in PyObject_Str that ensures it won't silently lose exception
627 * details.
628 */
629 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000630 if (sys_stderr != NULL && sys_stderr != Py_None) {
631 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
632 } else {
633 PyObject_Print(value, stderr, Py_PRINT_RAW);
634 fflush(stderr);
635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PySys_WriteStderr("\n");
637 exitcode = 1;
638 }
Victor Stinner12083282019-05-17 23:05:29 +0200639
Tim Peterscf615b52003-04-19 18:47:02 +0000640 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 /* Restore and clear the exception info, in order to properly decref
642 * the exception, value, and traceback. If we just exit instead,
643 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
644 * some finalizers from running.
645 */
646 PyErr_Restore(exception, value, tb);
647 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200648 *exitcode_p = exitcode;
649 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000650}
651
Victor Stinner12083282019-05-17 23:05:29 +0200652
653static void
654handle_system_exit(void)
655{
656 int exitcode;
657 if (_Py_HandleSystemExit(&exitcode)) {
658 Py_Exit(exitcode);
659 }
660}
661
662
Victor Stinner438a12d2019-05-24 17:01:38 +0200663static void
664_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000667
Victor Stinner12083282019-05-17 23:05:29 +0200668 handle_system_exit();
669
Victor Stinner438a12d2019-05-24 17:01:38 +0200670 _PyErr_Fetch(tstate, &exception, &v, &tb);
671 if (exception == NULL) {
672 goto done;
673 }
674
675 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 if (tb == NULL) {
677 tb = Py_None;
678 Py_INCREF(tb);
679 }
680 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200681 if (exception == NULL) {
682 goto done;
683 }
684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 /* Now we know v != NULL too */
686 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200687 if (_PySys_SetObjectId(&PyId_last_type, exception) < 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_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200691 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200692 }
693 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200694 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200695 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 }
Victor Stinner09054372013-11-06 22:41:44 +0100697 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100698 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
699 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800700 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
701 PyErr_Clear();
702 goto done;
703 }
704 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
705 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200707 PyObject* stack[3];
708 PyObject *result;
709
710 stack[0] = exception;
711 stack[1] = v;
712 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200713 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200715 handle_system_exit();
716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200718 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
719 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 /* It should not be possible for exception2 or v2
721 to be NULL. However PyErr_Display() can't
722 tolerate NULLs, so just be safe. */
723 if (exception2 == NULL) {
724 exception2 = Py_None;
725 Py_INCREF(exception2);
726 }
727 if (v2 == NULL) {
728 v2 = Py_None;
729 Py_INCREF(v2);
730 }
731 fflush(stdout);
732 PySys_WriteStderr("Error in sys.excepthook:\n");
733 PyErr_Display(exception2, v2, tb2);
734 PySys_WriteStderr("\nOriginal exception was:\n");
735 PyErr_Display(exception, v, tb);
736 Py_DECREF(exception2);
737 Py_DECREF(v2);
738 Py_XDECREF(tb2);
739 }
740 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200741 }
742 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PySys_WriteStderr("sys.excepthook is missing\n");
744 PyErr_Display(exception, v, tb);
745 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200746
747done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 Py_XDECREF(exception);
749 Py_XDECREF(v);
750 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000751}
752
Victor Stinner438a12d2019-05-24 17:01:38 +0200753void
754_PyErr_Print(PyThreadState *tstate)
755{
756 _PyErr_PrintEx(tstate, 1);
757}
758
759void
760PyErr_PrintEx(int set_sys_last_vars)
761{
762 PyThreadState *tstate = _PyThreadState_GET();
763 _PyErr_PrintEx(tstate, set_sys_last_vars);
764}
765
766void
767PyErr_Print(void)
768{
769 PyErr_PrintEx(1);
770}
771
Benjamin Petersone6528212008-07-15 15:32:09 +0000772static void
773print_exception(PyObject *f, PyObject *value)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 int err = 0;
776 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200777 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100780 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
781 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
782 err += PyFile_WriteString(" found\n", f);
783 if (err)
784 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 return;
786 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 Py_INCREF(value);
789 fflush(stdout);
790 type = (PyObject *) Py_TYPE(value);
791 tb = PyException_GetTraceback(value);
792 if (tb && tb != Py_None)
793 err = PyTraceBack_Print(tb, f);
794 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200795 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100797 PyObject *message, *filename, *text;
Ammar Askar90d29702020-06-02 08:17:24 +0000798 Py_ssize_t lineno, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (!parse_syntax_error(value, &message, &filename,
800 &lineno, &offset, &text))
801 PyErr_Clear();
802 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100803 PyObject *line;
804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 Py_DECREF(value);
806 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100807
Ammar Askar90d29702020-06-02 08:17:24 +0000808 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100809 filename, lineno);
810 Py_DECREF(filename);
811 if (line != NULL) {
812 PyFile_WriteObject(line, f, Py_PRINT_RAW);
813 Py_DECREF(line);
814 }
815
816 if (text != NULL) {
817 print_error_text(f, offset, text);
818 Py_DECREF(text);
819 }
820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 /* Can't be bothered to check all those
822 PyFile_WriteString() calls */
823 if (PyErr_Occurred())
824 err = -1;
825 }
826 }
827 if (err) {
828 /* Don't do anything else */
829 }
830 else {
831 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300832 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200833 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 assert(PyExceptionClass_Check(type));
835 className = PyExceptionClass_Name(type);
836 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300837 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (dot != NULL)
839 className = dot+1;
840 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000841
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200842 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 if (moduleName == NULL || !PyUnicode_Check(moduleName))
844 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200845 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 err = PyFile_WriteString("<unknown>", f);
847 }
848 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200849 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 {
Victor Stinner937114f2013-11-07 00:12:30 +0100851 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 err += PyFile_WriteString(".", f);
853 }
854 Py_DECREF(moduleName);
855 }
856 if (err == 0) {
857 if (className == NULL)
858 err = PyFile_WriteString("<unknown>", f);
859 else
860 err = PyFile_WriteString(className, f);
861 }
862 }
863 if (err == 0 && (value != Py_None)) {
864 PyObject *s = PyObject_Str(value);
865 /* only print colon if the str() of the
866 object is not the empty string
867 */
Martin Panter3263f682016-02-28 03:16:11 +0000868 if (s == NULL) {
869 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000871 PyFile_WriteString(": <exception str() failed>", f);
872 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100874 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 err = PyFile_WriteString(": ", f);
876 if (err == 0)
877 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
878 Py_XDECREF(s);
879 }
880 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000881 if (err < 0) {
882 PyErr_Clear();
883 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 err += PyFile_WriteString("\n", f);
885 Py_XDECREF(tb);
886 Py_DECREF(value);
887 /* If an error happened here, don't show it.
888 XXX This is wrong, but too many callers rely on this behavior. */
889 if (err != 0)
890 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000891}
892
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200893static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 "\nThe above exception was the direct cause "
895 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000896
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200897static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 "\nDuring handling of the above exception, "
899 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000900
901static void
902print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 int err = 0, res;
905 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 if (seen != NULL) {
908 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400909 PyObject *value_id = PyLong_FromVoidPtr(value);
910 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 PyErr_Clear();
912 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400913 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 cause = PyException_GetCause(value);
915 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700916 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -0400917 check_id = PyLong_FromVoidPtr(cause);
918 if (check_id == NULL) {
919 res = -1;
920 } else {
921 res = PySet_Contains(seen, check_id);
922 Py_DECREF(check_id);
923 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (res == -1)
925 PyErr_Clear();
926 if (res == 0) {
927 print_exception_recursive(
928 f, cause, seen);
929 err |= PyFile_WriteString(
930 cause_message, f);
931 }
932 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700933 else if (context &&
934 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -0400935 check_id = PyLong_FromVoidPtr(context);
936 if (check_id == NULL) {
937 res = -1;
938 } else {
939 res = PySet_Contains(seen, check_id);
940 Py_DECREF(check_id);
941 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (res == -1)
943 PyErr_Clear();
944 if (res == 0) {
945 print_exception_recursive(
946 f, context, seen);
947 err |= PyFile_WriteString(
948 context_message, f);
949 }
950 }
951 Py_XDECREF(context);
952 Py_XDECREF(cause);
953 }
Zane Bitterde860732017-10-17 17:29:39 -0400954 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 }
956 print_exception(f, value);
957 if (err != 0)
958 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000959}
960
Thomas Wouters477c8d52006-05-27 19:21:47 +0000961void
Victor Stinnercd590a72019-05-28 00:39:52 +0200962_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000963{
Victor Stinnercd590a72019-05-28 00:39:52 +0200964 assert(file != NULL && file != Py_None);
965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +0200967 if (PyExceptionInstance_Check(value)
968 && tb != NULL && PyTraceBack_Check(tb)) {
969 /* Put the traceback on the exception, otherwise it won't get
970 displayed. See issue #18776. */
971 PyObject *cur_tb = PyException_GetTraceback(value);
972 if (cur_tb == NULL)
973 PyException_SetTraceback(value, tb);
974 else
975 Py_DECREF(cur_tb);
976 }
Victor Stinnercd590a72019-05-28 00:39:52 +0200977
978 /* We choose to ignore seen being possibly NULL, and report
979 at least the main exception (it could be a MemoryError).
980 */
981 seen = PySet_New(NULL);
982 if (seen == NULL) {
983 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 }
Victor Stinnercd590a72019-05-28 00:39:52 +0200985 print_exception_recursive(file, value, seen);
986 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +0200987
988 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200989 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +0200990 if (!res) {
991 /* Silently ignore file.flush() error */
992 PyErr_Clear();
993 }
994 else {
995 Py_DECREF(res);
996 }
Victor Stinnercd590a72019-05-28 00:39:52 +0200997}
998
999void
1000PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1001{
1002 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1003 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 _PyObject_Dump(value);
1005 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001006 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001008 if (file == Py_None) {
1009 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001011
1012 _PyErr_Display(file, exception, value, tb);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001013}
1014
Guido van Rossum82598051997-03-05 00:20:32 +00001015PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001016PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyObject *ret = NULL;
1020 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001021 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001022 PyObject *filename;
1023
1024 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1025 if (filename == NULL)
1026 return NULL;
1027
1028 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (arena == NULL)
1030 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001031
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01001032 mod = PyPegen_ASTFromStringObject(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001035 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyArena_Free(arena);
1037 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001038}
1039
1040PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001041PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001043{
Victor Stinner95701bd2013-11-06 18:41:07 +01001044 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001046 PyArena *arena = NULL;
1047 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001048
Victor Stinner95701bd2013-11-06 18:41:07 +01001049 filename = PyUnicode_DecodeFSDefault(filename_str);
1050 if (filename == NULL)
1051 goto exit;
1052
1053 arena = PyArena_New();
1054 if (arena == NULL)
1055 goto exit;
1056
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01001057 mod = PyPegen_ASTFromFileObject(fp, filename, start, NULL, NULL, NULL,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001058 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 if (closeit)
1061 fclose(fp);
1062 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001063 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 }
1065 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01001066
1067exit:
1068 Py_XDECREF(filename);
1069 if (arena != NULL)
1070 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001072}
1073
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001074static void
1075flush_io(void)
1076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 PyObject *f, *r;
1078 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 /* Save the current exception */
1081 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001082
Victor Stinnerbd303c12013-11-07 23:07:29 +01001083 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001085 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 if (r)
1087 Py_DECREF(r);
1088 else
1089 PyErr_Clear();
1090 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001091 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001093 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (r)
1095 Py_DECREF(r);
1096 else
1097 PyErr_Clear();
1098 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001101}
1102
Guido van Rossum82598051997-03-05 00:20:32 +00001103static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001104run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001105{
1106 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001107 /*
1108 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1109 * _just in case_ someone is calling into an embedded Python where they
1110 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1111 * leave config.install_signal_handlers set to 0?!?) but then later call
1112 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1113 * its interpreter exits). We don't want a previous embedded interpreter's
1114 * uncaught exception to trigger an unexplained signal exit from a future
1115 * Py_Main() based one.
1116 */
1117 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001118
1119 /* Set globals['__builtins__'] if it doesn't exist */
1120 if (globals != NULL && PyDict_GetItemString(globals, "__builtins__") == NULL) {
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001121 if (PyDict_SetItemString(globals, "__builtins__",
1122 tstate->interp->builtins) < 0) {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001123 return NULL;
1124 }
1125 }
1126
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001127 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001128 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001129 _Py_UnhandledKeyboardInterrupt = 1;
1130 }
1131 return v;
1132}
1133
1134static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001135run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1136 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001137{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001138 PyThreadState *tstate = _PyThreadState_GET();
1139 PyCodeObject *co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 if (co == NULL)
1141 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001142
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001143 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001144 Py_DECREF(co);
1145 return NULL;
1146 }
1147
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001148 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 Py_DECREF(co);
1150 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001151}
1152
Guido van Rossum82598051997-03-05 00:20:32 +00001153static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001154run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001156{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001157 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 PyCodeObject *co;
1159 PyObject *v;
1160 long magic;
1161 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 magic = PyMarshal_ReadLongFromFile(fp);
1164 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001165 if (!PyErr_Occurred())
1166 PyErr_SetString(PyExc_RuntimeError,
1167 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001168 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001170 /* Skip the rest of the header. */
1171 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001172 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001174 if (PyErr_Occurred()) {
1175 goto error;
1176 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (v == NULL || !PyCode_Check(v)) {
1179 Py_XDECREF(v);
1180 PyErr_SetString(PyExc_RuntimeError,
1181 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001182 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 }
Zackery Spytzea737752018-06-23 21:15:24 -06001184 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001186 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 if (v && flags)
1188 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1189 Py_DECREF(co);
1190 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001191error:
1192 fclose(fp);
1193 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001194}
1195
Guido van Rossum82598051997-03-05 00:20:32 +00001196PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001197Py_CompileStringObject(const char *str, PyObject *filename, int start,
1198 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyCodeObject *co;
1201 mod_ty mod;
1202 PyArena *arena = PyArena_New();
1203 if (arena == NULL)
1204 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001205
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01001206 mod = PyPegen_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (mod == NULL) {
1208 PyArena_Free(arena);
1209 return NULL;
1210 }
1211 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1212 PyObject *result = PyAST_mod2obj(mod);
1213 PyArena_Free(arena);
1214 return result;
1215 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001216 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 PyArena_Free(arena);
1218 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001219}
1220
Victor Stinner14e461d2013-08-26 22:28:21 +02001221PyObject *
1222Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1223 PyCompilerFlags *flags, int optimize)
1224{
1225 PyObject *filename, *co;
1226 filename = PyUnicode_DecodeFSDefault(filename_str);
1227 if (filename == NULL)
1228 return NULL;
1229 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1230 Py_DECREF(filename);
1231 return co;
1232}
1233
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001234/* For use in Py_LIMITED_API */
1235#undef Py_CompileString
1236PyObject *
1237PyCompileString(const char *str, const char *filename, int start)
1238{
1239 return Py_CompileStringFlags(str, filename, start, NULL);
1240}
1241
Dino Viehland41540692019-05-28 16:21:17 -07001242const char *
1243_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1244{
1245 const char *str;
1246 Py_ssize_t size;
1247 Py_buffer view;
1248
1249 *cmd_copy = NULL;
1250 if (PyUnicode_Check(cmd)) {
1251 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1252 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1253 if (str == NULL)
1254 return NULL;
1255 }
1256 else if (PyBytes_Check(cmd)) {
1257 str = PyBytes_AS_STRING(cmd);
1258 size = PyBytes_GET_SIZE(cmd);
1259 }
1260 else if (PyByteArray_Check(cmd)) {
1261 str = PyByteArray_AS_STRING(cmd);
1262 size = PyByteArray_GET_SIZE(cmd);
1263 }
1264 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1265 /* Copy to NUL-terminated buffer. */
1266 *cmd_copy = PyBytes_FromStringAndSize(
1267 (const char *)view.buf, view.len);
1268 PyBuffer_Release(&view);
1269 if (*cmd_copy == NULL) {
1270 return NULL;
1271 }
1272 str = PyBytes_AS_STRING(*cmd_copy);
1273 size = PyBytes_GET_SIZE(*cmd_copy);
1274 }
1275 else {
1276 PyErr_Format(PyExc_TypeError,
1277 "%s() arg 1 must be a %s object",
1278 funcname, what);
1279 return NULL;
1280 }
1281
1282 if (strlen(str) != (size_t)size) {
1283 PyErr_SetString(PyExc_ValueError,
1284 "source code string cannot contain null bytes");
1285 Py_CLEAR(*cmd_copy);
1286 return NULL;
1287 }
1288 return str;
1289}
1290
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001291struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02001292Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001293{
Victor Stinner37d66d72019-06-13 02:16:41 +02001294 PyCompilerFlags flags = _PyCompilerFlags_INIT;
Dino Viehland41540692019-05-28 16:21:17 -07001295 return _Py_SymtableStringObjectFlags(str, filename, start, &flags);
1296}
1297
1298struct symtable *
1299_Py_SymtableStringObjectFlags(const char *str, PyObject *filename, int start, PyCompilerFlags *flags)
1300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 struct symtable *st;
1302 mod_ty mod;
Victor Stinner14e461d2013-08-26 22:28:21 +02001303 PyArena *arena;
1304
1305 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (arena == NULL)
1307 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001308
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01001309 mod = PyPegen_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (mod == NULL) {
1311 PyArena_Free(arena);
1312 return NULL;
1313 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001314 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 PyArena_Free(arena);
1316 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001317}
1318
Victor Stinner14e461d2013-08-26 22:28:21 +02001319struct symtable *
1320Py_SymtableString(const char *str, const char *filename_str, int start)
1321{
1322 PyObject *filename;
1323 struct symtable *st;
1324
1325 filename = PyUnicode_DecodeFSDefault(filename_str);
1326 if (filename == NULL)
1327 return NULL;
1328 st = Py_SymtableStringObject(str, filename, start);
1329 Py_DECREF(filename);
1330 return st;
1331}
1332
Zachary Warec4821d62014-11-21 23:35:12 -06001333#if defined(USE_STACKCHECK)
1334#if defined(WIN32) && defined(_MSC_VER)
1335
1336/* Stack checking for Microsoft C */
1337
1338#include <malloc.h>
1339#include <excpt.h>
1340
1341/*
1342 * Return non-zero when we run out of memory on the stack; zero otherwise.
1343 */
1344int
1345PyOS_CheckStack(void)
1346{
1347 __try {
1348 /* alloca throws a stack overflow exception if there's
1349 not enough space left on the stack */
1350 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1351 return 0;
1352 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1353 EXCEPTION_EXECUTE_HANDLER :
1354 EXCEPTION_CONTINUE_SEARCH) {
1355 int errcode = _resetstkoflw();
1356 if (errcode == 0)
1357 {
1358 Py_FatalError("Could not reset the stack!");
1359 }
1360 }
1361 return 1;
1362}
1363
1364#endif /* WIN32 && _MSC_VER */
1365
1366/* Alternate implementations can be added here... */
1367
1368#endif /* USE_STACKCHECK */
1369
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001370#ifdef __cplusplus
1371}
1372#endif