blob: dacf1a647106fb822531b6bdcc5d58cf881e4c5e [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 *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010062static PyObject *run_pyc_file(FILE *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
xdegayee0582a32017-11-12 16:50:48 +010064static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010065static PyObject* pyrun_file(FILE *fp, PyObject *filename, int start,
66 PyObject *globals, PyObject *locals, int closeit,
67 PyCompilerFlags *flags);
68
Guido van Rossumce3a72a2007-10-19 23:16:50 +000069
Victor Stinnera82f63f2020-12-09 22:37:27 +010070int
71_PyRun_AnyFileObject(FILE *fp, PyObject *filename, int closeit,
72 PyCompilerFlags *flags)
73{
74 int decref_filename = 0;
75 if (filename == NULL) {
76 filename = PyUnicode_FromString("???");
77 if (filename == NULL) {
78 PyErr_Print();
79 return -1;
80 }
81 decref_filename = 1;
82 }
83
84 int res;
85 if (_Py_FdIsInteractive(fp, filename)) {
86 res = _PyRun_InteractiveLoopObject(fp, filename, flags);
87 if (closeit) {
88 fclose(fp);
89 }
90 }
91 else {
92 res = _PyRun_SimpleFileObject(fp, filename, closeit, flags);
93 }
94
95 if (decref_filename) {
96 Py_DECREF(filename);
97 }
98 return res;
99}
100
101
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000102/* Parse input from a file and execute it */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000103int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000104PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000106{
Victor Stinnera82f63f2020-12-09 22:37:27 +0100107 PyObject *filename_obj;
108 if (filename != NULL) {
109 filename_obj = PyUnicode_DecodeFSDefault(filename);
110 if (filename_obj == NULL) {
111 PyErr_Print();
112 return -1;
113 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100115 else {
116 filename_obj = NULL;
117 }
118 int res = _PyRun_AnyFileObject(fp, filename_obj, closeit, flags);
119 Py_XDECREF(filename_obj);
120 return res;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000121}
122
Victor Stinnera82f63f2020-12-09 22:37:27 +0100123
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000124int
Victor Stinnera82f63f2020-12-09 22:37:27 +0100125_PyRun_InteractiveLoopObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000126{
Victor Stinner37d66d72019-06-13 02:16:41 +0200127 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 if (flags == NULL) {
129 flags = &local_flags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100131
132 PyObject *v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100134 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 Py_XDECREF(v);
136 }
Victor Stinner09054372013-11-06 22:41:44 +0100137 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100139 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 Py_XDECREF(v);
141 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100142
143#ifdef Py_REF_DEBUG
144 int show_ref_count = _Py_GetConfig()->show_ref_count;
145#endif
146 int err = 0;
147 int ret;
148 int nomem_count = 0;
xdegayee0582a32017-11-12 16:50:48 +0100149 do {
150 ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
151 if (ret == -1 && PyErr_Occurred()) {
152 /* Prevent an endless loop after multiple consecutive MemoryErrors
153 * while still allowing an interactive command to fail with a
154 * MemoryError. */
155 if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
156 if (++nomem_count > 16) {
157 PyErr_Clear();
158 err = -1;
159 break;
160 }
161 } else {
162 nomem_count = 0;
163 }
164 PyErr_Print();
165 flush_io();
166 } else {
167 nomem_count = 0;
168 }
Eric Snowdae02762017-09-14 00:35:58 -0700169#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -0800170 if (show_ref_count) {
Eric Snowdae02762017-09-14 00:35:58 -0700171 _PyDebug_PrintTotalRefs();
Victor Stinner25420fe2017-11-20 18:12:22 -0800172 }
Eric Snowdae02762017-09-14 00:35:58 -0700173#endif
xdegayee0582a32017-11-12 16:50:48 +0100174 } while (ret != E_EOF);
Victor Stinner95701bd2013-11-06 18:41:07 +0100175 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000176}
177
Victor Stinnera82f63f2020-12-09 22:37:27 +0100178
179int
180PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
181{
182 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
183 if (filename_obj == NULL) {
184 PyErr_Print();
185 return -1;
186 }
187
188 int err = _PyRun_InteractiveLoopObject(fp, filename_obj, flags);
189 Py_DECREF(filename_obj);
190 return err;
191
192}
193
194
xdegayee0582a32017-11-12 16:50:48 +0100195/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
196 * error on failure. */
197static int
198PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
199 PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000200{
Victor Stinner95701bd2013-11-06 18:41:07 +0100201 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 mod_ty mod;
203 PyArena *arena;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200204 const char *ps1 = "", *ps2 = "", *enc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200206 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +0100207 _Py_IDENTIFIER(__main__);
208
209 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
210 if (mod_name == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100211 return -1;
212 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400215 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +0100216 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400217 if (v && v != Py_None) {
218 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
219 if (oenc)
Serhiy Storchaka06515832016-11-20 09:13:07 +0200220 enc = PyUnicode_AsUTF8(oenc);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400221 if (!enc)
222 PyErr_Clear();
223 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 }
Victor Stinner09054372013-11-06 22:41:44 +0100225 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (v != NULL) {
227 v = PyObject_Str(v);
228 if (v == NULL)
229 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000230 else if (PyUnicode_Check(v)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200231 ps1 = PyUnicode_AsUTF8(v);
Victor Stinner386fe712010-05-19 00:34:15 +0000232 if (ps1 == NULL) {
233 PyErr_Clear();
234 ps1 = "";
235 }
236 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 }
Victor Stinner09054372013-11-06 22:41:44 +0100238 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (w != NULL) {
240 w = PyObject_Str(w);
241 if (w == NULL)
242 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000243 else if (PyUnicode_Check(w)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200244 ps2 = PyUnicode_AsUTF8(w);
Victor Stinner386fe712010-05-19 00:34:15 +0000245 if (ps2 == NULL) {
246 PyErr_Clear();
247 ps2 = "";
248 }
249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 }
251 arena = PyArena_New();
252 if (arena == NULL) {
253 Py_XDECREF(v);
254 Py_XDECREF(w);
255 Py_XDECREF(oenc);
256 return -1;
257 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100258
Lysandros Nikolaou564cd182020-06-22 02:47:46 +0300259 mod = PyParser_ASTFromFileObject(fp, filename, enc, Py_single_input,
260 ps1, ps2, flags, &errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 Py_XDECREF(v);
263 Py_XDECREF(w);
264 Py_XDECREF(oenc);
265 if (mod == NULL) {
266 PyArena_Free(arena);
267 if (errcode == E_EOF) {
268 PyErr_Clear();
269 return E_EOF;
270 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 return -1;
272 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100273 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 if (m == NULL) {
275 PyArena_Free(arena);
276 return -1;
277 }
278 d = PyModule_GetDict(m);
279 v = run_mod(mod, filename, d, d, flags, arena);
280 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 return -1;
283 }
284 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200285 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000287}
288
Victor Stinner95701bd2013-11-06 18:41:07 +0100289int
xdegayee0582a32017-11-12 16:50:48 +0100290PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
291{
292 int res;
293
294 res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
295 if (res == -1) {
296 PyErr_Print();
297 flush_io();
298 }
299 return res;
300}
301
302int
Victor Stinner95701bd2013-11-06 18:41:07 +0100303PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
304{
305 PyObject *filename;
306 int res;
307
308 filename = PyUnicode_DecodeFSDefault(filename_str);
309 if (filename == NULL) {
310 PyErr_Print();
311 return -1;
312 }
313 res = PyRun_InteractiveOneObject(fp, filename, flags);
314 Py_DECREF(filename);
315 return res;
316}
317
318
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000319/* Check whether a file maybe a pyc file: Look at the extension,
320 the file type, and, if we may close it, at the first few bytes. */
321
322static int
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100323maybe_pyc_file(FILE *fp, PyObject *filename, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000324{
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100325 PyObject *ext = PyUnicode_FromString(".pyc");
326 if (ext == NULL) {
327 return -1;
328 }
329 Py_ssize_t endswith = PyUnicode_Tailmatch(filename, ext, 0, PY_SSIZE_T_MAX, +1);
330 Py_DECREF(ext);
331 if (endswith) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 return 1;
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100333 }
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* Only look into the file if we are allowed to close it, since
336 it then should also be seekable. */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100337 if (!closeit) {
338 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100340
341 /* Read only two bytes of the magic. If the file was opened in
342 text mode, the bytes 3 and 4 of the magic (\r\n) might not
343 be read as they are on disk. */
344 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
345 unsigned char buf[2];
346 /* Mess: In case of -x, the stream is NOT at its start now,
347 and ungetc() was used to push back the first newline,
348 which makes the current stream position formally undefined,
349 and a x-platform nightmare.
350 Unfortunately, we have no direct way to know whether -x
351 was specified. So we use a terrible hack: if the current
352 stream position is not 0, we assume -x was specified, and
353 give up. Bug 132850 on SourceForge spells out the
354 hopelessness of trying anything else (fseek and ftell
355 don't work predictably x-platform for text-mode files).
356 */
357 int ispyc = 0;
358 if (ftell(fp) == 0) {
359 if (fread(buf, 1, 2, fp) == 2 &&
360 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
361 ispyc = 1;
362 rewind(fp);
363 }
364 return ispyc;
Tim Petersd08e3822003-04-17 15:24:21 +0000365}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000366
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200367
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100368static int
369set_main_loader(PyObject *d, PyObject *filename, const char *loader_name)
370{
Victor Stinner81a7be32020-04-14 15:14:01 +0200371 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100372 PyObject *bootstrap = PyObject_GetAttrString(interp->importlib,
373 "_bootstrap_external");
374 if (bootstrap == NULL) {
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000375 return -1;
376 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100377
378 PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
379 Py_DECREF(bootstrap);
380 if (loader_type == NULL) {
381 return -1;
382 }
383
384 PyObject *loader = PyObject_CallFunction(loader_type,
385 "sO", "__main__", filename);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000386 Py_DECREF(loader_type);
387 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000388 return -1;
389 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100390
Nick Coghlanb7a58942012-07-15 23:21:08 +1000391 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100392 Py_DECREF(loader);
393 return -1;
Nick Coghlanb7a58942012-07-15 23:21:08 +1000394 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000395 Py_DECREF(loader);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100396 return 0;
Nick Coghlan85e729e2012-07-15 18:09:52 +1000397}
398
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100399
Victor Stinner550e4672020-12-09 00:32:54 +0100400int
401_PyRun_SimpleFileObject(FILE *fp, PyObject *filename, int closeit,
402 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 PyObject *m, *d, *v;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100405 int set_file_name = 0, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 m = PyImport_AddModule("__main__");
408 if (m == NULL)
409 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100410 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 d = PyModule_GetDict(m);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200412 if (_PyDict_GetItemStringWithError(d, "__file__") == NULL) {
413 if (PyErr_Occurred()) {
414 goto done;
415 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100416 if (PyDict_SetItemString(d, "__file__", filename) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100417 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 }
Barry Warsaw916048d2011-09-20 14:45:44 -0400419 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100420 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -0400421 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 set_file_name = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100424
425 int pyc = maybe_pyc_file(fp, filename, closeit);
426 if (pyc < 0) {
427 goto done;
428 }
429
430 if (pyc) {
Christian Heimes04ac4c12012-09-11 15:47:28 +0200431 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 /* Try to run a pyc file. First, re-open in binary */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100433 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 fclose(fp);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100435 }
436
437 pyc_fp = _Py_fopen_obj(filename, "rb");
438 if (pyc_fp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 goto done;
441 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000442
443 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
444 fprintf(stderr, "python: failed to set __main__.__loader__\n");
445 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +0200446 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +1000447 goto done;
448 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100449 v = run_pyc_file(pyc_fp, d, d, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000451 /* When running from stdin, leave __main__.__loader__ alone */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100452 if (PyUnicode_CompareWithASCIIString(filename, "<stdin>") != 0 &&
Nick Coghlan85e729e2012-07-15 18:09:52 +1000453 set_main_loader(d, filename, "SourceFileLoader") < 0) {
454 fprintf(stderr, "python: failed to set __main__.__loader__\n");
455 ret = -1;
456 goto done;
457 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100458 v = pyrun_file(fp, filename, Py_file_input, d, d,
459 closeit, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 }
461 flush_io();
462 if (v == NULL) {
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600463 Py_CLEAR(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 goto done;
466 }
467 Py_DECREF(v);
468 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000469 done:
INADA Naoki82daa602018-11-29 20:01:27 +0900470 if (set_file_name) {
471 if (PyDict_DelItemString(d, "__file__")) {
472 PyErr_Clear();
473 }
474 if (PyDict_DelItemString(d, "__cached__")) {
475 PyErr_Clear();
476 }
477 }
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600478 Py_XDECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000480}
481
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100482
483int
484PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
485 PyCompilerFlags *flags)
486{
487 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
488 if (filename_obj == NULL) {
489 return -1;
490 }
Victor Stinner550e4672020-12-09 00:32:54 +0100491 int res = _PyRun_SimpleFileObject(fp, filename_obj, closeit, flags);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100492 Py_DECREF(filename_obj);
493 return res;
494}
495
496
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000497int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000498PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 PyObject *m, *d, *v;
501 m = PyImport_AddModule("__main__");
502 if (m == NULL)
503 return -1;
504 d = PyModule_GetDict(m);
505 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
506 if (v == NULL) {
507 PyErr_Print();
508 return -1;
509 }
510 Py_DECREF(v);
511 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000512}
513
Barry Warsaw035574d1997-08-29 22:07:17 +0000514static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100515parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
Ammar Askar90d29702020-06-02 08:17:24 +0000516 Py_ssize_t *lineno, Py_ssize_t *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000517{
Ammar Askar90d29702020-06-02 08:17:24 +0000518 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200520 _Py_IDENTIFIER(msg);
521 _Py_IDENTIFIER(filename);
522 _Py_IDENTIFIER(lineno);
523 _Py_IDENTIFIER(offset);
524 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000525
Benjamin Peterson80d50422012-04-03 00:30:38 -0400526 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100527 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400530 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400531 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000533
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400534 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400535 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400537 if (v == Py_None) {
538 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100539 *filename = _PyUnicode_FromId(&PyId_string);
540 if (*filename == NULL)
541 goto finally;
542 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400543 }
544 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100545 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400546 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000547
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400548 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400549 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000551 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 if (hold < 0 && PyErr_Occurred())
554 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300555 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000556
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400557 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400558 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 goto finally;
560 if (v == Py_None) {
561 *offset = -1;
562 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000564 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (hold < 0 && PyErr_Occurred())
567 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300568 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000570
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400571 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400572 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400574 if (v == Py_None) {
575 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400577 }
578 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100579 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400580 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000582
583finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400584 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100585 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000587}
588
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000589static void
Ammar Askar90d29702020-06-02 08:17:24 +0000590print_error_text(PyObject *f, Py_ssize_t offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000591{
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700592 /* Convert text to a char pointer; return if error */
593 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100594 if (text == NULL)
595 return;
596
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700597 /* Convert offset from 1-based to 0-based */
598 offset--;
599
600 /* Strip leading whitespace from text, adjusting offset as we go */
601 while (*text == ' ' || *text == '\t' || *text == '\f') {
602 text++;
603 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700605
606 /* Calculate text length excluding trailing newline */
607 Py_ssize_t len = strlen(text);
608 if (len > 0 && text[len-1] == '\n') {
609 len--;
610 }
611
612 /* Clip offset to at most len */
613 if (offset > len) {
614 offset = len;
615 }
616
617 /* Skip past newlines embedded in text */
618 for (;;) {
619 const char *nl = strchr(text, '\n');
620 if (nl == NULL) {
621 break;
622 }
623 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000624 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700625 break;
626 }
627 inl += 1;
628 text += inl;
629 len -= inl;
630 offset -= (int)inl;
631 }
632
633 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 PyFile_WriteString(" ", f);
635 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700636
637 /* Make sure there's a newline at the end */
638 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700640 }
641
642 /* Don't print caret if it points to the left of the text */
643 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700645
646 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700648 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700650 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000652}
653
Tim Peterscf615b52003-04-19 18:47:02 +0000654
Victor Stinner12083282019-05-17 23:05:29 +0200655int
656_Py_HandleSystemExit(int *exitcode_p)
657{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200658 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200659 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 /* Don't exit if -i flag was given. This flag is set to 0
661 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200662 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200663 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000664
Victor Stinner12083282019-05-17 23:05:29 +0200665 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
666 return 0;
667 }
668
669 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200673
674 int exitcode = 0;
675 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200677 }
678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 if (PyExceptionInstance_Check(value)) {
680 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200681 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200682 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 if (code) {
684 Py_DECREF(value);
685 value = code;
686 if (value == Py_None)
687 goto done;
688 }
689 /* If we failed to dig out the 'code' attribute,
690 just let the else clause below print the error. */
691 }
Victor Stinner12083282019-05-17 23:05:29 +0200692
693 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200695 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100697 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000698 /* We clear the exception here to avoid triggering the assertion
699 * in PyObject_Str that ensures it won't silently lose exception
700 * details.
701 */
702 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000703 if (sys_stderr != NULL && sys_stderr != Py_None) {
704 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
705 } else {
706 PyObject_Print(value, stderr, Py_PRINT_RAW);
707 fflush(stderr);
708 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PySys_WriteStderr("\n");
710 exitcode = 1;
711 }
Victor Stinner12083282019-05-17 23:05:29 +0200712
Tim Peterscf615b52003-04-19 18:47:02 +0000713 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 /* Restore and clear the exception info, in order to properly decref
715 * the exception, value, and traceback. If we just exit instead,
716 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
717 * some finalizers from running.
718 */
719 PyErr_Restore(exception, value, tb);
720 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200721 *exitcode_p = exitcode;
722 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000723}
724
Victor Stinner12083282019-05-17 23:05:29 +0200725
726static void
727handle_system_exit(void)
728{
729 int exitcode;
730 if (_Py_HandleSystemExit(&exitcode)) {
731 Py_Exit(exitcode);
732 }
733}
734
735
Victor Stinner438a12d2019-05-24 17:01:38 +0200736static void
737_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000740
Victor Stinner12083282019-05-17 23:05:29 +0200741 handle_system_exit();
742
Victor Stinner438a12d2019-05-24 17:01:38 +0200743 _PyErr_Fetch(tstate, &exception, &v, &tb);
744 if (exception == NULL) {
745 goto done;
746 }
747
748 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (tb == NULL) {
750 tb = Py_None;
751 Py_INCREF(tb);
752 }
753 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200754 if (exception == NULL) {
755 goto done;
756 }
757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* Now we know v != NULL too */
759 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200760 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200761 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200762 }
763 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200764 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200765 }
766 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200767 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200768 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 }
Victor Stinner09054372013-11-06 22:41:44 +0100770 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100771 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
772 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800773 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
774 PyErr_Clear();
775 goto done;
776 }
777 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
778 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200780 PyObject* stack[3];
781 PyObject *result;
782
783 stack[0] = exception;
784 stack[1] = v;
785 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200786 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200788 handle_system_exit();
789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200791 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
792 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 /* It should not be possible for exception2 or v2
794 to be NULL. However PyErr_Display() can't
795 tolerate NULLs, so just be safe. */
796 if (exception2 == NULL) {
797 exception2 = Py_None;
798 Py_INCREF(exception2);
799 }
800 if (v2 == NULL) {
801 v2 = Py_None;
802 Py_INCREF(v2);
803 }
804 fflush(stdout);
805 PySys_WriteStderr("Error in sys.excepthook:\n");
806 PyErr_Display(exception2, v2, tb2);
807 PySys_WriteStderr("\nOriginal exception was:\n");
808 PyErr_Display(exception, v, tb);
809 Py_DECREF(exception2);
810 Py_DECREF(v2);
811 Py_XDECREF(tb2);
812 }
813 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200814 }
815 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 PySys_WriteStderr("sys.excepthook is missing\n");
817 PyErr_Display(exception, v, tb);
818 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200819
820done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 Py_XDECREF(exception);
822 Py_XDECREF(v);
823 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000824}
825
Victor Stinner438a12d2019-05-24 17:01:38 +0200826void
827_PyErr_Print(PyThreadState *tstate)
828{
829 _PyErr_PrintEx(tstate, 1);
830}
831
832void
833PyErr_PrintEx(int set_sys_last_vars)
834{
835 PyThreadState *tstate = _PyThreadState_GET();
836 _PyErr_PrintEx(tstate, set_sys_last_vars);
837}
838
839void
840PyErr_Print(void)
841{
842 PyErr_PrintEx(1);
843}
844
Benjamin Petersone6528212008-07-15 15:32:09 +0000845static void
846print_exception(PyObject *f, PyObject *value)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 int err = 0;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300849 PyObject *type, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200850 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100853 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
854 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
855 err += PyFile_WriteString(" found\n", f);
856 if (err)
857 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 return;
859 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 Py_INCREF(value);
862 fflush(stdout);
863 type = (PyObject *) Py_TYPE(value);
864 tb = PyException_GetTraceback(value);
865 if (tb && tb != Py_None)
866 err = PyTraceBack_Print(tb, f);
867 if (err == 0 &&
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300868 (err = _PyObject_LookupAttrId(value, &PyId_print_file_and_line, &tmp)) > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100870 PyObject *message, *filename, *text;
Ammar Askar90d29702020-06-02 08:17:24 +0000871 Py_ssize_t lineno, offset;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300872 err = 0;
873 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (!parse_syntax_error(value, &message, &filename,
875 &lineno, &offset, &text))
876 PyErr_Clear();
877 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100878 PyObject *line;
879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 Py_DECREF(value);
881 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100882
Ammar Askar90d29702020-06-02 08:17:24 +0000883 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100884 filename, lineno);
885 Py_DECREF(filename);
886 if (line != NULL) {
887 PyFile_WriteObject(line, f, Py_PRINT_RAW);
888 Py_DECREF(line);
889 }
890
891 if (text != NULL) {
892 print_error_text(f, offset, text);
893 Py_DECREF(text);
894 }
895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 /* Can't be bothered to check all those
897 PyFile_WriteString() calls */
898 if (PyErr_Occurred())
899 err = -1;
900 }
901 }
902 if (err) {
903 /* Don't do anything else */
904 }
905 else {
906 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300907 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200908 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 assert(PyExceptionClass_Check(type));
910 className = PyExceptionClass_Name(type);
911 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300912 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (dot != NULL)
914 className = dot+1;
915 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000916
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200917 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (moduleName == NULL || !PyUnicode_Check(moduleName))
919 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200920 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 err = PyFile_WriteString("<unknown>", f);
922 }
923 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200924 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 {
Victor Stinner937114f2013-11-07 00:12:30 +0100926 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 err += PyFile_WriteString(".", f);
928 }
929 Py_DECREF(moduleName);
930 }
931 if (err == 0) {
932 if (className == NULL)
933 err = PyFile_WriteString("<unknown>", f);
934 else
935 err = PyFile_WriteString(className, f);
936 }
937 }
938 if (err == 0 && (value != Py_None)) {
939 PyObject *s = PyObject_Str(value);
940 /* only print colon if the str() of the
941 object is not the empty string
942 */
Martin Panter3263f682016-02-28 03:16:11 +0000943 if (s == NULL) {
944 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000946 PyFile_WriteString(": <exception str() failed>", f);
947 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100949 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 err = PyFile_WriteString(": ", f);
951 if (err == 0)
952 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
953 Py_XDECREF(s);
954 }
955 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000956 if (err < 0) {
957 PyErr_Clear();
958 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 err += PyFile_WriteString("\n", f);
960 Py_XDECREF(tb);
961 Py_DECREF(value);
962 /* If an error happened here, don't show it.
963 XXX This is wrong, but too many callers rely on this behavior. */
964 if (err != 0)
965 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000966}
967
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200968static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 "\nThe above exception was the direct cause "
970 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000971
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200972static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 "\nDuring handling of the above exception, "
974 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000975
976static void
977print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 int err = 0, res;
980 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (seen != NULL) {
983 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400984 PyObject *value_id = PyLong_FromVoidPtr(value);
985 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyErr_Clear();
987 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400988 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 cause = PyException_GetCause(value);
990 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700991 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -0400992 check_id = PyLong_FromVoidPtr(cause);
993 if (check_id == NULL) {
994 res = -1;
995 } else {
996 res = PySet_Contains(seen, check_id);
997 Py_DECREF(check_id);
998 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 if (res == -1)
1000 PyErr_Clear();
1001 if (res == 0) {
1002 print_exception_recursive(
1003 f, cause, seen);
1004 err |= PyFile_WriteString(
1005 cause_message, f);
1006 }
1007 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001008 else if (context &&
1009 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -04001010 check_id = PyLong_FromVoidPtr(context);
1011 if (check_id == NULL) {
1012 res = -1;
1013 } else {
1014 res = PySet_Contains(seen, check_id);
1015 Py_DECREF(check_id);
1016 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (res == -1)
1018 PyErr_Clear();
1019 if (res == 0) {
1020 print_exception_recursive(
1021 f, context, seen);
1022 err |= PyFile_WriteString(
1023 context_message, f);
1024 }
1025 }
1026 Py_XDECREF(context);
1027 Py_XDECREF(cause);
1028 }
Zane Bitterde860732017-10-17 17:29:39 -04001029 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 }
1031 print_exception(f, value);
1032 if (err != 0)
1033 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001034}
1035
Thomas Wouters477c8d52006-05-27 19:21:47 +00001036void
Victor Stinnercd590a72019-05-28 00:39:52 +02001037_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001038{
Victor Stinnercd590a72019-05-28 00:39:52 +02001039 assert(file != NULL && file != Py_None);
1040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +02001042 if (PyExceptionInstance_Check(value)
1043 && tb != NULL && PyTraceBack_Check(tb)) {
1044 /* Put the traceback on the exception, otherwise it won't get
1045 displayed. See issue #18776. */
1046 PyObject *cur_tb = PyException_GetTraceback(value);
1047 if (cur_tb == NULL)
1048 PyException_SetTraceback(value, tb);
1049 else
1050 Py_DECREF(cur_tb);
1051 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001052
1053 /* We choose to ignore seen being possibly NULL, and report
1054 at least the main exception (it could be a MemoryError).
1055 */
1056 seen = PySet_New(NULL);
1057 if (seen == NULL) {
1058 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001060 print_exception_recursive(file, value, seen);
1061 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001062
1063 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001064 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001065 if (!res) {
1066 /* Silently ignore file.flush() error */
1067 PyErr_Clear();
1068 }
1069 else {
1070 Py_DECREF(res);
1071 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001072}
1073
1074void
1075PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1076{
1077 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1078 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 _PyObject_Dump(value);
1080 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001081 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001083 if (file == Py_None) {
1084 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001086
1087 _PyErr_Display(file, exception, value, tb);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001088}
1089
Guido van Rossum82598051997-03-05 00:20:32 +00001090PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001091PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyObject *ret = NULL;
1095 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001096 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001097 PyObject *filename;
1098
1099 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1100 if (filename == NULL)
1101 return NULL;
1102
1103 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 if (arena == NULL)
1105 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001106
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001107 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001110 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyArena_Free(arena);
1112 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001113}
1114
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001115
1116static PyObject *
1117pyrun_file(FILE *fp, PyObject *filename, int start, PyObject *globals,
1118 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001119{
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001120 PyArena *arena = PyArena_New();
1121 if (arena == NULL) {
1122 return NULL;
1123 }
1124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 mod_ty mod;
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001126 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, NULL, NULL,
1127 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001128
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001129 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001132
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001133 PyObject *ret;
1134 if (mod != NULL) {
1135 ret = run_mod(mod, filename, globals, locals, flags, arena);
1136 }
1137 else {
1138 ret = NULL;
1139 }
1140 PyArena_Free(arena);
1141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001143}
1144
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001145
1146PyObject *
1147PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1148 PyObject *locals, int closeit, PyCompilerFlags *flags)
1149{
1150 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
1151 if (filename_obj == NULL) {
1152 return NULL;
1153 }
1154
1155 PyObject *res = pyrun_file(fp, filename_obj, start, globals,
1156 locals, closeit, flags);
1157 Py_DECREF(filename_obj);
1158 return res;
1159
1160}
1161
1162
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001163static void
1164flush_io(void)
1165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 PyObject *f, *r;
1167 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 /* Save the current exception */
1170 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001171
Victor Stinnerbd303c12013-11-07 23:07:29 +01001172 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001174 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (r)
1176 Py_DECREF(r);
1177 else
1178 PyErr_Clear();
1179 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001180 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001182 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (r)
1184 Py_DECREF(r);
1185 else
1186 PyErr_Clear();
1187 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001190}
1191
Guido van Rossum82598051997-03-05 00:20:32 +00001192static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001193run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001194{
1195 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001196 /*
1197 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1198 * _just in case_ someone is calling into an embedded Python where they
1199 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1200 * leave config.install_signal_handlers set to 0?!?) but then later call
1201 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1202 * its interpreter exits). We don't want a previous embedded interpreter's
1203 * uncaught exception to trigger an unexplained signal exit from a future
1204 * Py_Main() based one.
1205 */
1206 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001207
1208 /* Set globals['__builtins__'] if it doesn't exist */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001209 if (globals != NULL && _PyDict_GetItemStringWithError(globals, "__builtins__") == NULL) {
1210 if (PyErr_Occurred() ||
1211 PyDict_SetItemString(globals, "__builtins__",
1212 tstate->interp->builtins) < 0)
1213 {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001214 return NULL;
1215 }
1216 }
1217
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001218 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001219 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001220 _Py_UnhandledKeyboardInterrupt = 1;
1221 }
1222 return v;
1223}
1224
1225static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001226run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1227 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001228{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001229 PyThreadState *tstate = _PyThreadState_GET();
1230 PyCodeObject *co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (co == NULL)
1232 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001233
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001234 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001235 Py_DECREF(co);
1236 return NULL;
1237 }
1238
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001239 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 Py_DECREF(co);
1241 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001242}
1243
Guido van Rossum82598051997-03-05 00:20:32 +00001244static PyObject *
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001245run_pyc_file(FILE *fp, PyObject *globals, PyObject *locals,
1246 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001247{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001248 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 PyCodeObject *co;
1250 PyObject *v;
1251 long magic;
1252 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 magic = PyMarshal_ReadLongFromFile(fp);
1255 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001256 if (!PyErr_Occurred())
1257 PyErr_SetString(PyExc_RuntimeError,
1258 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001259 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001261 /* Skip the rest of the header. */
1262 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001263 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001265 if (PyErr_Occurred()) {
1266 goto error;
1267 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (v == NULL || !PyCode_Check(v)) {
1270 Py_XDECREF(v);
1271 PyErr_SetString(PyExc_RuntimeError,
1272 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001273 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 }
Zackery Spytzea737752018-06-23 21:15:24 -06001275 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001277 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (v && flags)
1279 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1280 Py_DECREF(co);
1281 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001282error:
1283 fclose(fp);
1284 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001285}
1286
Guido van Rossum82598051997-03-05 00:20:32 +00001287PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001288Py_CompileStringObject(const char *str, PyObject *filename, int start,
1289 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 PyCodeObject *co;
1292 mod_ty mod;
1293 PyArena *arena = PyArena_New();
1294 if (arena == NULL)
1295 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001296
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001297 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (mod == NULL) {
1299 PyArena_Free(arena);
1300 return NULL;
1301 }
1302 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1303 PyObject *result = PyAST_mod2obj(mod);
1304 PyArena_Free(arena);
1305 return result;
1306 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001307 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 PyArena_Free(arena);
1309 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001310}
1311
Victor Stinner14e461d2013-08-26 22:28:21 +02001312PyObject *
1313Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1314 PyCompilerFlags *flags, int optimize)
1315{
1316 PyObject *filename, *co;
1317 filename = PyUnicode_DecodeFSDefault(filename_str);
1318 if (filename == NULL)
1319 return NULL;
1320 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1321 Py_DECREF(filename);
1322 return co;
1323}
1324
Dino Viehland41540692019-05-28 16:21:17 -07001325const char *
1326_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1327{
1328 const char *str;
1329 Py_ssize_t size;
1330 Py_buffer view;
1331
1332 *cmd_copy = NULL;
1333 if (PyUnicode_Check(cmd)) {
1334 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1335 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1336 if (str == NULL)
1337 return NULL;
1338 }
1339 else if (PyBytes_Check(cmd)) {
1340 str = PyBytes_AS_STRING(cmd);
1341 size = PyBytes_GET_SIZE(cmd);
1342 }
1343 else if (PyByteArray_Check(cmd)) {
1344 str = PyByteArray_AS_STRING(cmd);
1345 size = PyByteArray_GET_SIZE(cmd);
1346 }
1347 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1348 /* Copy to NUL-terminated buffer. */
1349 *cmd_copy = PyBytes_FromStringAndSize(
1350 (const char *)view.buf, view.len);
1351 PyBuffer_Release(&view);
1352 if (*cmd_copy == NULL) {
1353 return NULL;
1354 }
1355 str = PyBytes_AS_STRING(*cmd_copy);
1356 size = PyBytes_GET_SIZE(*cmd_copy);
1357 }
1358 else {
1359 PyErr_Format(PyExc_TypeError,
1360 "%s() arg 1 must be a %s object",
1361 funcname, what);
1362 return NULL;
1363 }
1364
1365 if (strlen(str) != (size_t)size) {
1366 PyErr_SetString(PyExc_ValueError,
1367 "source code string cannot contain null bytes");
1368 Py_CLEAR(*cmd_copy);
1369 return NULL;
1370 }
1371 return str;
1372}
1373
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001374struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02001375Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001376{
Victor Stinner37d66d72019-06-13 02:16:41 +02001377 PyCompilerFlags flags = _PyCompilerFlags_INIT;
Dino Viehland41540692019-05-28 16:21:17 -07001378 return _Py_SymtableStringObjectFlags(str, filename, start, &flags);
1379}
1380
1381struct symtable *
1382_Py_SymtableStringObjectFlags(const char *str, PyObject *filename, int start, PyCompilerFlags *flags)
1383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 struct symtable *st;
1385 mod_ty mod;
Victor Stinner14e461d2013-08-26 22:28:21 +02001386 PyArena *arena;
1387
1388 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 if (arena == NULL)
1390 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001391
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001392 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (mod == NULL) {
1394 PyArena_Free(arena);
1395 return NULL;
1396 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001397 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyArena_Free(arena);
1399 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001400}
1401
Victor Stinner14e461d2013-08-26 22:28:21 +02001402struct symtable *
1403Py_SymtableString(const char *str, const char *filename_str, int start)
1404{
1405 PyObject *filename;
1406 struct symtable *st;
1407
1408 filename = PyUnicode_DecodeFSDefault(filename_str);
1409 if (filename == NULL)
1410 return NULL;
1411 st = Py_SymtableStringObject(str, filename, start);
1412 Py_DECREF(filename);
1413 return st;
1414}
1415
Zachary Warec4821d62014-11-21 23:35:12 -06001416#if defined(USE_STACKCHECK)
1417#if defined(WIN32) && defined(_MSC_VER)
1418
1419/* Stack checking for Microsoft C */
1420
1421#include <malloc.h>
1422#include <excpt.h>
1423
1424/*
1425 * Return non-zero when we run out of memory on the stack; zero otherwise.
1426 */
1427int
1428PyOS_CheckStack(void)
1429{
1430 __try {
1431 /* alloca throws a stack overflow exception if there's
1432 not enough space left on the stack */
1433 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1434 return 0;
1435 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1436 EXCEPTION_EXECUTE_HANDLER :
1437 EXCEPTION_CONTINUE_SEARCH) {
1438 int errcode = _resetstkoflw();
1439 if (errcode == 0)
1440 {
1441 Py_FatalError("Could not reset the stack!");
1442 }
1443 }
1444 return 1;
1445}
1446
1447#endif /* WIN32 && _MSC_VER */
1448
1449/* Alternate implementations can be added here... */
1450
1451#endif /* USE_STACKCHECK */
1452
Pablo Galindo46bd5ed2020-12-02 05:16:31 +00001453/* Deprecated C API functions still provided for binary compatibility */
1454
1455#undef PyRun_AnyFile
1456PyAPI_FUNC(int)
1457PyRun_AnyFile(FILE *fp, const char *name)
1458{
1459 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1460}
1461
1462#undef PyRun_AnyFileEx
1463PyAPI_FUNC(int)
1464PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1465{
1466 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1467}
1468
1469#undef PyRun_AnyFileFlags
1470PyAPI_FUNC(int)
1471PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1472{
1473 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1474}
1475
1476#undef PyRun_File
1477PyAPI_FUNC(PyObject *)
1478PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1479{
1480 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1481}
1482
1483#undef PyRun_FileEx
1484PyAPI_FUNC(PyObject *)
1485PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1486{
1487 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1488}
1489
1490#undef PyRun_FileFlags
1491PyAPI_FUNC(PyObject *)
1492PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1493 PyCompilerFlags *flags)
1494{
1495 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1496}
1497
1498#undef PyRun_SimpleFile
1499PyAPI_FUNC(int)
1500PyRun_SimpleFile(FILE *f, const char *p)
1501{
1502 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1503}
1504
1505#undef PyRun_SimpleFileEx
1506PyAPI_FUNC(int)
1507PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1508{
1509 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1510}
1511
1512
1513#undef PyRun_String
1514PyAPI_FUNC(PyObject *)
1515PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1516{
1517 return PyRun_StringFlags(str, s, g, l, NULL);
1518}
1519
1520#undef PyRun_SimpleString
1521PyAPI_FUNC(int)
1522PyRun_SimpleString(const char *s)
1523{
1524 return PyRun_SimpleStringFlags(s, NULL);
1525}
1526
1527#undef Py_CompileString
1528PyAPI_FUNC(PyObject *)
1529Py_CompileString(const char *str, const char *p, int s)
1530{
1531 return Py_CompileStringExFlags(str, p, s, NULL, -1);
1532}
1533
1534#undef Py_CompileStringFlags
1535PyAPI_FUNC(PyObject *)
1536Py_CompileStringFlags(const char *str, const char *p, int s,
1537 PyCompilerFlags *flags)
1538{
1539 return Py_CompileStringExFlags(str, p, s, flags, -1);
1540}
1541
1542#undef PyRun_InteractiveOne
1543PyAPI_FUNC(int)
1544PyRun_InteractiveOne(FILE *f, const char *p)
1545{
1546 return PyRun_InteractiveOneFlags(f, p, NULL);
1547}
1548
1549#undef PyRun_InteractiveLoop
1550PyAPI_FUNC(int)
1551PyRun_InteractiveLoop(FILE *f, const char *p)
1552{
1553 return PyRun_InteractiveLoopFlags(f, p, NULL);
1554}
1555
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001556#ifdef __cplusplus
1557}
1558#endif