2 /* Top level execution of Python code (including in __main__) */
4 /* To help control the interfaces between the startup, execution and
5 * shutdown code, the phases are split across separate modules (bootstrap,
9 /* TODO: Cull includes following phase split */
15 #include "pycore_ast.h" // PyAST_mod2obj()
16 #include "pycore_ceval.h" // _Py_EnterRecursiveCall()
17 #include "pycore_compile.h" // _PyAST_Compile()
18 #include "pycore_interp.h" // PyInterpreterState.importlib
19 #include "pycore_object.h" // _PyDebug_PrintTotalRefs()
20 #include "pycore_parser.h" // _PyParser_ASTFromString()
21 #include "pycore_pyerrors.h" // _PyErr_GetRaisedException()
22 #include "pycore_pylifecycle.h" // _Py_FdIsInteractive()
23 #include "pycore_pystate.h" // _PyInterpreterState_GET()
24 #include "pycore_pythonrun.h" // export _PyRun_InteractiveLoopObject()
25 #include "pycore_sysmodule.h" // _PySys_Audit()
26 #include "pycore_traceback.h" // _PyTraceBack_Print()
28 #include "errcode.h" // E_EOF
29 #include "marshal.h" // PyMarshal_ReadLongFromFile()
32 # include "malloc.h" // alloca()
41 static void flush_io(void);
42 static PyObject
*run_mod(mod_ty
, PyObject
*, PyObject
*, PyObject
*,
43 PyCompilerFlags
*, PyArena
*, PyObject
*, int);
44 static PyObject
*run_pyc_file(FILE *, PyObject
*, PyObject
*,
46 static int PyRun_InteractiveOneObjectEx(FILE *, PyObject
*, PyCompilerFlags
*);
47 static PyObject
* pyrun_file(FILE *fp
, PyObject
*filename
, int start
,
48 PyObject
*globals
, PyObject
*locals
, int closeit
,
49 PyCompilerFlags
*flags
);
51 _PyRun_StringFlagsWithName(const char *str
, PyObject
* name
, int start
,
52 PyObject
*globals
, PyObject
*locals
, PyCompilerFlags
*flags
,
53 int generate_new_source
);
56 _PyRun_AnyFileObject(FILE *fp
, PyObject
*filename
, int closeit
,
57 PyCompilerFlags
*flags
)
59 int decref_filename
= 0;
60 if (filename
== NULL
) {
61 filename
= PyUnicode_FromString("???");
62 if (filename
== NULL
) {
70 if (_Py_FdIsInteractive(fp
, filename
)) {
71 res
= _PyRun_InteractiveLoopObject(fp
, filename
, flags
);
77 res
= _PyRun_SimpleFileObject(fp
, filename
, closeit
, flags
);
80 if (decref_filename
) {
87 /* Parse input from a file and execute it */
89 PyRun_AnyFileExFlags(FILE *fp
, const char *filename
, int closeit
,
90 PyCompilerFlags
*flags
)
92 PyObject
*filename_obj
= NULL
;
93 if (filename
!= NULL
) {
94 filename_obj
= PyUnicode_DecodeFSDefault(filename
);
95 if (filename_obj
== NULL
) {
100 int res
= _PyRun_AnyFileObject(fp
, filename_obj
, closeit
, flags
);
101 Py_XDECREF(filename_obj
);
107 _PyRun_InteractiveLoopObject(FILE *fp
, PyObject
*filename
, PyCompilerFlags
*flags
)
109 PyCompilerFlags local_flags
= _PyCompilerFlags_INIT
;
111 flags
= &local_flags
;
114 PyThreadState
*tstate
= _PyThreadState_GET();
115 PyObject
*v
= _PySys_GetAttr(tstate
, &_Py_ID(ps1
));
117 _PySys_SetAttr(&_Py_ID(ps1
), v
= PyUnicode_FromString(">>> "));
120 v
= _PySys_GetAttr(tstate
, &_Py_ID(ps2
));
122 _PySys_SetAttr(&_Py_ID(ps2
), v
= PyUnicode_FromString("... "));
127 int show_ref_count
= _Py_GetConfig()->show_ref_count
;
133 ret
= PyRun_InteractiveOneObjectEx(fp
, filename
, flags
);
134 if (ret
== -1 && PyErr_Occurred()) {
135 /* Prevent an endless loop after multiple consecutive MemoryErrors
136 * while still allowing an interactive command to fail with a
138 if (PyErr_ExceptionMatches(PyExc_MemoryError
)) {
139 if (++nomem_count
> 16) {
153 if (show_ref_count
) {
154 _PyDebug_PrintTotalRefs();
157 } while (ret
!= E_EOF
);
163 PyRun_InteractiveLoopFlags(FILE *fp
, const char *filename
, PyCompilerFlags
*flags
)
165 PyObject
*filename_obj
= PyUnicode_DecodeFSDefault(filename
);
166 if (filename_obj
== NULL
) {
171 int err
= _PyRun_InteractiveLoopObject(fp
, filename_obj
, flags
);
172 Py_DECREF(filename_obj
);
178 // Call _PyParser_ASTFromFile() with sys.stdin.encoding, sys.ps1 and sys.ps2
180 pyrun_one_parse_ast(FILE *fp
, PyObject
*filename
,
181 PyCompilerFlags
*flags
, PyArena
*arena
,
182 mod_ty
*pmod
, PyObject
** interactive_src
)
184 PyThreadState
*tstate
= _PyThreadState_GET();
186 // Get sys.stdin.encoding (as UTF-8)
187 PyObject
*attr
; // borrowed ref
188 PyObject
*encoding_obj
= NULL
;
189 const char *encoding
= NULL
;
191 attr
= _PySys_GetAttr(tstate
, &_Py_ID(stdin
));
192 if (attr
&& attr
!= Py_None
) {
193 encoding_obj
= PyObject_GetAttr(attr
, &_Py_ID(encoding
));
195 encoding
= PyUnicode_AsUTF8(encoding_obj
);
203 // Get sys.ps1 (as UTF-8)
204 attr
= _PySys_GetAttr(tstate
, &_Py_ID(ps1
));
205 PyObject
*ps1_obj
= NULL
;
206 const char *ps1
= "";
208 ps1_obj
= PyObject_Str(attr
);
209 if (ps1_obj
== NULL
) {
212 else if (PyUnicode_Check(ps1_obj
)) {
213 ps1
= PyUnicode_AsUTF8(ps1_obj
);
221 // Get sys.ps2 (as UTF-8)
222 attr
= _PySys_GetAttr(tstate
, &_Py_ID(ps2
));
223 PyObject
*ps2_obj
= NULL
;
224 const char *ps2
= "";
226 ps2_obj
= PyObject_Str(attr
);
227 if (ps2_obj
== NULL
) {
230 else if (PyUnicode_Check(ps2_obj
)) {
231 ps2
= PyUnicode_AsUTF8(ps2_obj
);
240 *pmod
= _PyParser_InteractiveASTFromFile(fp
, filename
, encoding
,
241 Py_single_input
, ps1
, ps2
,
242 flags
, &errcode
, interactive_src
, arena
);
245 Py_XDECREF(encoding_obj
);
248 if (errcode
== E_EOF
) {
258 /* A PyRun_InteractiveOneObject() auxiliary function that does not print the
259 * error on failure. */
261 PyRun_InteractiveOneObjectEx(FILE *fp
, PyObject
*filename
,
262 PyCompilerFlags
*flags
)
264 PyArena
*arena
= _PyArena_New();
270 PyObject
*interactive_src
;
271 int parse_res
= pyrun_one_parse_ast(fp
, filename
, flags
, arena
, &mod
, &interactive_src
);
272 if (parse_res
!= 0) {
273 _PyArena_Free(arena
);
277 PyObject
*main_module
= PyImport_AddModuleRef("__main__");
278 if (main_module
== NULL
) {
279 _PyArena_Free(arena
);
282 PyObject
*main_dict
= PyModule_GetDict(main_module
); // borrowed ref
284 PyObject
*res
= run_mod(mod
, filename
, main_dict
, main_dict
, flags
, arena
, interactive_src
, 1);
285 _PyArena_Free(arena
);
286 Py_DECREF(main_module
);
297 PyRun_InteractiveOneObject(FILE *fp
, PyObject
*filename
, PyCompilerFlags
*flags
)
301 res
= PyRun_InteractiveOneObjectEx(fp
, filename
, flags
);
310 PyRun_InteractiveOneFlags(FILE *fp
, const char *filename_str
, PyCompilerFlags
*flags
)
315 filename
= PyUnicode_DecodeFSDefault(filename_str
);
316 if (filename
== NULL
) {
320 res
= PyRun_InteractiveOneObject(fp
, filename
, flags
);
326 /* Check whether a file maybe a pyc file: Look at the extension,
327 the file type, and, if we may close it, at the first few bytes. */
330 maybe_pyc_file(FILE *fp
, PyObject
*filename
, int closeit
)
332 PyObject
*ext
= PyUnicode_FromString(".pyc");
336 Py_ssize_t endswith
= PyUnicode_Tailmatch(filename
, ext
, 0, PY_SSIZE_T_MAX
, +1);
342 /* Only look into the file if we are allowed to close it, since
343 it then should also be seekable. */
348 /* Read only two bytes of the magic. If the file was opened in
349 text mode, the bytes 3 and 4 of the magic (\r\n) might not
350 be read as they are on disk. */
351 unsigned int halfmagic
= PyImport_GetMagicNumber() & 0xFFFF;
352 unsigned char buf
[2];
353 /* Mess: In case of -x, the stream is NOT at its start now,
354 and ungetc() was used to push back the first newline,
355 which makes the current stream position formally undefined,
356 and a x-platform nightmare.
357 Unfortunately, we have no direct way to know whether -x
358 was specified. So we use a terrible hack: if the current
359 stream position is not 0, we assume -x was specified, and
360 give up. Bug 132850 on SourceForge spells out the
361 hopelessness of trying anything else (fseek and ftell
362 don't work predictably x-platform for text-mode files).
365 if (ftell(fp
) == 0) {
366 if (fread(buf
, 1, 2, fp
) == 2 &&
367 ((unsigned int)buf
[1]<<8 | buf
[0]) == halfmagic
)
376 set_main_loader(PyObject
*d
, PyObject
*filename
, const char *loader_name
)
378 PyInterpreterState
*interp
= _PyInterpreterState_GET();
379 PyObject
*loader_type
= _PyImport_GetImportlibExternalLoader(interp
,
381 if (loader_type
== NULL
) {
385 PyObject
*loader
= PyObject_CallFunction(loader_type
,
386 "sO", "__main__", filename
);
387 Py_DECREF(loader_type
);
388 if (loader
== NULL
) {
392 if (PyDict_SetItemString(d
, "__loader__", loader
) < 0) {
402 _PyRun_SimpleFileObject(FILE *fp
, PyObject
*filename
, int closeit
,
403 PyCompilerFlags
*flags
)
407 PyObject
*main_module
= PyImport_AddModuleRef("__main__");
408 if (main_module
== NULL
)
410 PyObject
*dict
= PyModule_GetDict(main_module
); // borrowed ref
412 int set_file_name
= 0;
413 int has_file
= PyDict_ContainsString(dict
, "__file__");
418 if (PyDict_SetItemString(dict
, "__file__", filename
) < 0) {
421 if (PyDict_SetItemString(dict
, "__cached__", Py_None
) < 0) {
427 int pyc
= maybe_pyc_file(fp
, filename
, closeit
);
435 /* Try to run a pyc file. First, re-open in binary */
440 pyc_fp
= _Py_fopen_obj(filename
, "rb");
441 if (pyc_fp
== NULL
) {
442 fprintf(stderr
, "python: Can't reopen .pyc file\n");
446 if (set_main_loader(dict
, filename
, "SourcelessFileLoader") < 0) {
447 fprintf(stderr
, "python: failed to set __main__.__loader__\n");
452 v
= run_pyc_file(pyc_fp
, dict
, dict
, flags
);
454 /* When running from stdin, leave __main__.__loader__ alone */
455 if ((!PyUnicode_Check(filename
) || !PyUnicode_EqualToUTF8(filename
, "<stdin>")) &&
456 set_main_loader(dict
, filename
, "SourceFileLoader") < 0) {
457 fprintf(stderr
, "python: failed to set __main__.__loader__\n");
461 v
= pyrun_file(fp
, filename
, Py_file_input
, dict
, dict
,
466 Py_CLEAR(main_module
);
475 if (PyDict_PopString(dict
, "__file__", NULL
) < 0) {
478 if (PyDict_PopString(dict
, "__cached__", NULL
) < 0) {
482 Py_XDECREF(main_module
);
488 PyRun_SimpleFileExFlags(FILE *fp
, const char *filename
, int closeit
,
489 PyCompilerFlags
*flags
)
491 PyObject
*filename_obj
= PyUnicode_DecodeFSDefault(filename
);
492 if (filename_obj
== NULL
) {
495 int res
= _PyRun_SimpleFileObject(fp
, filename_obj
, closeit
, flags
);
496 Py_DECREF(filename_obj
);
502 _PyRun_SimpleStringFlagsWithName(const char *command
, const char* name
, PyCompilerFlags
*flags
) {
503 PyObject
*main_module
= PyImport_AddModuleRef("__main__");
504 if (main_module
== NULL
) {
507 PyObject
*dict
= PyModule_GetDict(main_module
); // borrowed ref
509 PyObject
*res
= NULL
;
511 res
= PyRun_StringFlags(command
, Py_file_input
, dict
, dict
, flags
);
513 PyObject
* the_name
= PyUnicode_FromString(name
);
518 res
= _PyRun_StringFlagsWithName(command
, the_name
, Py_file_input
, dict
, dict
, flags
, 0);
521 Py_DECREF(main_module
);
532 PyRun_SimpleStringFlags(const char *command
, PyCompilerFlags
*flags
)
534 return _PyRun_SimpleStringFlagsWithName(command
, NULL
, flags
);
538 _Py_HandleSystemExit(int *exitcode_p
)
540 int inspect
= _Py_GetConfig()->inspect
;
542 /* Don't exit if -i flag was given. This flag is set to 0
543 * when entering interactive mode for inspecting. */
547 if (!PyErr_ExceptionMatches(PyExc_SystemExit
)) {
555 PyObject
*exc
= PyErr_GetRaisedException();
559 assert(PyExceptionInstance_Check(exc
));
561 /* The error code should be in the `code' attribute. */
562 PyObject
*code
= PyObject_GetAttr(exc
, &_Py_ID(code
));
564 Py_SETREF(exc
, code
);
565 if (exc
== Py_None
) {
569 /* If we failed to dig out the 'code' attribute,
570 * just let the else clause below print the error.
573 if (PyLong_Check(exc
)) {
574 exitcode
= (int)PyLong_AsLong(exc
);
577 PyThreadState
*tstate
= _PyThreadState_GET();
578 PyObject
*sys_stderr
= _PySys_GetAttr(tstate
, &_Py_ID(stderr
));
579 /* We clear the exception here to avoid triggering the assertion
580 * in PyObject_Str that ensures it won't silently lose exception
584 if (sys_stderr
!= NULL
&& sys_stderr
!= Py_None
) {
585 PyFile_WriteObject(exc
, sys_stderr
, Py_PRINT_RAW
);
587 PyObject_Print(exc
, stderr
, Py_PRINT_RAW
);
590 PySys_WriteStderr("\n");
596 *exitcode_p
= exitcode
;
602 handle_system_exit(void)
605 if (_Py_HandleSystemExit(&exitcode
)) {
612 _PyErr_PrintEx(PyThreadState
*tstate
, int set_sys_last_vars
)
614 PyObject
*typ
= NULL
, *tb
= NULL
;
615 handle_system_exit();
617 PyObject
*exc
= _PyErr_GetRaisedException(tstate
);
621 assert(PyExceptionInstance_Check(exc
));
622 typ
= Py_NewRef(Py_TYPE(exc
));
623 tb
= PyException_GetTraceback(exc
);
625 tb
= Py_NewRef(Py_None
);
628 if (set_sys_last_vars
) {
629 if (_PySys_SetAttr(&_Py_ID(last_exc
), exc
) < 0) {
630 _PyErr_Clear(tstate
);
632 /* Legacy version: */
633 if (_PySys_SetAttr(&_Py_ID(last_type
), typ
) < 0) {
634 _PyErr_Clear(tstate
);
636 if (_PySys_SetAttr(&_Py_ID(last_value
), exc
) < 0) {
637 _PyErr_Clear(tstate
);
639 if (_PySys_SetAttr(&_Py_ID(last_traceback
), tb
) < 0) {
640 _PyErr_Clear(tstate
);
643 PyObject
*hook
= _PySys_GetAttr(tstate
, &_Py_ID(excepthook
));
644 if (_PySys_Audit(tstate
, "sys.excepthook", "OOOO", hook
? hook
: Py_None
,
646 if (PyErr_ExceptionMatches(PyExc_RuntimeError
)) {
650 PyErr_FormatUnraisable("Exception ignored in audit hook");
653 PyObject
* args
[3] = {typ
, exc
, tb
};
654 PyObject
*result
= PyObject_Vectorcall(hook
, args
, 3, NULL
);
655 if (result
== NULL
) {
656 handle_system_exit();
658 PyObject
*exc2
= _PyErr_GetRaisedException(tstate
);
659 assert(exc2
&& PyExceptionInstance_Check(exc2
));
661 PySys_WriteStderr("Error in sys.excepthook:\n");
662 PyErr_DisplayException(exc2
);
663 PySys_WriteStderr("\nOriginal exception was:\n");
664 PyErr_DisplayException(exc
);
672 PySys_WriteStderr("sys.excepthook is missing\n");
673 PyErr_DisplayException(exc
);
683 _PyErr_Print(PyThreadState
*tstate
)
685 _PyErr_PrintEx(tstate
, 1);
689 PyErr_PrintEx(int set_sys_last_vars
)
691 PyThreadState
*tstate
= _PyThreadState_GET();
692 _PyErr_PrintEx(tstate
, set_sys_last_vars
);
701 struct exception_print_context
704 PyObject
*seen
; // Prevent cycles in recursion
708 print_exception_invalid_type(struct exception_print_context
*ctx
,
711 PyObject
*f
= ctx
->file
;
712 const char *const msg
= "TypeError: print_exception(): Exception expected "
714 if (PyFile_WriteString(msg
, f
) < 0) {
717 if (PyFile_WriteString(Py_TYPE(value
)->tp_name
, f
) < 0) {
720 if (PyFile_WriteString(" found\n", f
) < 0) {
727 print_exception_traceback(struct exception_print_context
*ctx
, PyObject
*value
)
729 PyObject
*f
= ctx
->file
;
732 PyObject
*tb
= PyException_GetTraceback(value
);
733 if (tb
&& tb
!= Py_None
) {
734 const char *header
= EXCEPTION_TB_HEADER
;
735 err
= _PyTraceBack_Print(tb
, header
, f
);
742 print_exception_file_and_line(struct exception_print_context
*ctx
,
745 PyObject
*f
= ctx
->file
;
748 int res
= PyObject_GetOptionalAttr(*value_p
, &_Py_ID(print_file_and_line
), &tmp
);
757 PyObject
*filename
= NULL
;
758 Py_ssize_t lineno
= 0;
759 PyObject
* v
= PyObject_GetAttr(*value_p
, &_Py_ID(filename
));
765 _Py_DECLARE_STR(anon_string
, "<string>");
766 filename
= Py_NewRef(&_Py_STR(anon_string
));
772 PyObject
*line
= PyUnicode_FromFormat(" File \"%S\", line %zd\n",
778 if (PyFile_WriteObject(line
, f
, Py_PRINT_RAW
) < 0) {
783 assert(!PyErr_Occurred());
791 /* Prints the message line: module.qualname[: str(exc)] */
793 print_exception_message(struct exception_print_context
*ctx
, PyObject
*type
,
796 PyObject
*f
= ctx
->file
;
798 if (PyErr_GivenExceptionMatches(value
, PyExc_MemoryError
)) {
799 // The Python APIs in this function require allocating memory
800 // for various objects. If we're out of memory, we can't do that,
804 assert(PyExceptionClass_Check(type
));
806 PyObject
*modulename
= PyObject_GetAttr(type
, &_Py_ID(__module__
));
807 if (modulename
== NULL
|| !PyUnicode_Check(modulename
)) {
808 Py_XDECREF(modulename
);
810 if (PyFile_WriteString("<unknown>.", f
) < 0) {
815 if (!_PyUnicode_Equal(modulename
, &_Py_ID(builtins
)) &&
816 !_PyUnicode_Equal(modulename
, &_Py_ID(__main__
)))
818 int res
= PyFile_WriteObject(modulename
, f
, Py_PRINT_RAW
);
819 Py_DECREF(modulename
);
823 if (PyFile_WriteString(".", f
) < 0) {
828 Py_DECREF(modulename
);
832 PyObject
*qualname
= PyType_GetQualName((PyTypeObject
*)type
);
833 if (qualname
== NULL
|| !PyUnicode_Check(qualname
)) {
834 Py_XDECREF(qualname
);
836 if (PyFile_WriteString("<unknown>", f
) < 0) {
841 int res
= PyFile_WriteObject(qualname
, f
, Py_PRINT_RAW
);
848 if (Py_IsNone(value
)) {
852 PyObject
*s
= PyObject_Str(value
);
855 if (PyFile_WriteString(": <exception str() failed>", f
) < 0) {
860 /* only print colon if the str() of the
861 object is not the empty string
863 if (!PyUnicode_Check(s
) || PyUnicode_GetLength(s
) != 0) {
864 if (PyFile_WriteString(": ", f
) < 0) {
869 int res
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
880 print_exception(struct exception_print_context
*ctx
, PyObject
*value
)
882 PyObject
*f
= ctx
->file
;
884 if (!PyExceptionInstance_Check(value
)) {
885 return print_exception_invalid_type(ctx
, value
);
891 if (print_exception_traceback(ctx
, value
) < 0) {
895 /* grab the type and notes now because value can change below */
896 PyObject
*type
= (PyObject
*) Py_TYPE(value
);
898 if (print_exception_file_and_line(ctx
, &value
) < 0) {
901 if (print_exception_message(ctx
, type
, value
) < 0) {
904 if (PyFile_WriteString("\n", f
) < 0) {
908 assert(!PyErr_Occurred());
915 static const char cause_message
[] =
916 "The above exception was the direct cause "
917 "of the following exception:\n";
919 static const char context_message
[] =
920 "During handling of the above exception, "
921 "another exception occurred:\n";
924 print_exception_recursive(struct exception_print_context
*, PyObject
*);
927 print_chained(struct exception_print_context
* ctx
, PyObject
*value
,
928 const char * message
, const char *tag
)
930 PyObject
*f
= ctx
->file
;
931 if (_Py_EnterRecursiveCall(" in print_chained")) {
934 int res
= print_exception_recursive(ctx
, value
);
935 _Py_LeaveRecursiveCall();
940 if (PyFile_WriteString("\n", f
) < 0) {
943 if (PyFile_WriteString(message
, f
) < 0) {
946 if (PyFile_WriteString("\n", f
) < 0) {
952 /* Return true if value is in seen or there was a lookup error.
953 * Return false if lookup succeeded and the item was not found.
954 * We suppress errors because this makes us err on the side of
955 * under-printing which is better than over-printing irregular
956 * exceptions (e.g., unhashable ones).
959 print_exception_seen_lookup(struct exception_print_context
*ctx
,
962 PyObject
*check_id
= PyLong_FromVoidPtr(value
);
963 if (check_id
== NULL
) {
968 int in_seen
= PySet_Contains(ctx
->seen
, check_id
);
976 /* value is in seen */
983 print_exception_cause_and_context(struct exception_print_context
*ctx
,
986 PyObject
*value_id
= PyLong_FromVoidPtr(value
);
987 if (value_id
== NULL
|| PySet_Add(ctx
->seen
, value_id
) == -1) {
989 Py_XDECREF(value_id
);
994 if (!PyExceptionInstance_Check(value
)) {
998 PyObject
*cause
= PyException_GetCause(value
);
1001 if (!print_exception_seen_lookup(ctx
, cause
)) {
1002 err
= print_chained(ctx
, cause
, cause_message
, "cause");
1007 if (((PyBaseExceptionObject
*)value
)->suppress_context
) {
1010 PyObject
*context
= PyException_GetContext(value
);
1013 if (!print_exception_seen_lookup(ctx
, context
)) {
1014 err
= print_chained(ctx
, context
, context_message
, "context");
1023 print_exception_recursive(struct exception_print_context
*ctx
, PyObject
*value
)
1025 if (_Py_EnterRecursiveCall(" in print_exception_recursive")) {
1028 if (ctx
->seen
!= NULL
) {
1029 /* Exception chaining */
1030 if (print_exception_cause_and_context(ctx
, value
) < 0) {
1034 if (print_exception(ctx
, value
) < 0) {
1037 assert(!PyErr_Occurred());
1039 _Py_LeaveRecursiveCall();
1042 _Py_LeaveRecursiveCall();
1047 _PyErr_Display(PyObject
*file
, PyObject
*unused
, PyObject
*value
, PyObject
*tb
)
1049 assert(value
!= NULL
);
1050 assert(file
!= NULL
&& file
!= Py_None
);
1051 if (PyExceptionInstance_Check(value
)
1052 && tb
!= NULL
&& PyTraceBack_Check(tb
)) {
1053 /* Put the traceback on the exception, otherwise it won't get
1054 displayed. See issue #18776. */
1055 PyObject
*cur_tb
= PyException_GetTraceback(value
);
1056 if (cur_tb
== NULL
) {
1057 PyException_SetTraceback(value
, tb
);
1064 int unhandled_keyboard_interrupt
= _PyRuntime
.signals
.unhandled_keyboard_interrupt
;
1066 // Try first with the stdlib traceback module
1067 PyObject
*traceback_module
= PyImport_ImportModule("traceback");
1069 if (traceback_module
== NULL
) {
1073 PyObject
*print_exception_fn
= PyObject_GetAttrString(traceback_module
, "_print_exception_bltin");
1075 if (print_exception_fn
== NULL
|| !PyCallable_Check(print_exception_fn
)) {
1076 Py_DECREF(traceback_module
);
1080 PyObject
* result
= PyObject_CallOneArg(print_exception_fn
, value
);
1082 Py_DECREF(traceback_module
);
1083 Py_XDECREF(print_exception_fn
);
1086 _PyRuntime
.signals
.unhandled_keyboard_interrupt
= unhandled_keyboard_interrupt
;
1090 _PyRuntime
.signals
.unhandled_keyboard_interrupt
= unhandled_keyboard_interrupt
;
1092 if (PyErr_Occurred()) {
1093 PyErr_FormatUnraisable(
1094 "Exception ignored in the internal traceback machinery");
1098 struct exception_print_context ctx
;
1101 /* We choose to ignore seen being possibly NULL, and report
1102 at least the main exception (it could be a MemoryError).
1104 ctx
.seen
= PySet_New(NULL
);
1105 if (ctx
.seen
== NULL
) {
1108 if (print_exception_recursive(&ctx
, value
) < 0) {
1110 _PyObject_Dump(value
);
1111 fprintf(stderr
, "lost sys.stderr\n");
1113 Py_XDECREF(ctx
.seen
);
1115 /* Call file.flush() */
1116 if (_PyFile_Flush(file
) < 0) {
1117 /* Silently ignore file.flush() error */
1123 PyErr_Display(PyObject
*unused
, PyObject
*value
, PyObject
*tb
)
1125 PyThreadState
*tstate
= _PyThreadState_GET();
1126 PyObject
*file
= _PySys_GetAttr(tstate
, &_Py_ID(stderr
));
1128 _PyObject_Dump(value
);
1129 fprintf(stderr
, "lost sys.stderr\n");
1132 if (file
== Py_None
) {
1136 _PyErr_Display(file
, NULL
, value
, tb
);
1140 void _PyErr_DisplayException(PyObject
*file
, PyObject
*exc
)
1142 _PyErr_Display(file
, NULL
, exc
, NULL
);
1145 void PyErr_DisplayException(PyObject
*exc
)
1147 PyErr_Display(NULL
, exc
, NULL
);
1151 _PyRun_StringFlagsWithName(const char *str
, PyObject
* name
, int start
,
1152 PyObject
*globals
, PyObject
*locals
, PyCompilerFlags
*flags
,
1153 int generate_new_source
)
1155 PyObject
*ret
= NULL
;
1159 arena
= _PyArena_New();
1163 PyObject
* source
= NULL
;
1164 _Py_DECLARE_STR(anon_string
, "<string>");
1167 source
= PyUnicode_FromString(str
);
1172 name
= &_Py_STR(anon_string
);
1175 mod
= _PyParser_ASTFromString(str
, name
, start
, flags
, arena
);
1178 ret
= run_mod(mod
, name
, globals
, locals
, flags
, arena
, source
, generate_new_source
);
1181 _PyArena_Free(arena
);
1187 PyRun_StringFlags(const char *str
, int start
, PyObject
*globals
,
1188 PyObject
*locals
, PyCompilerFlags
*flags
) {
1190 return _PyRun_StringFlagsWithName(str
, NULL
, start
, globals
, locals
, flags
, 0);
1194 pyrun_file(FILE *fp
, PyObject
*filename
, int start
, PyObject
*globals
,
1195 PyObject
*locals
, int closeit
, PyCompilerFlags
*flags
)
1197 PyArena
*arena
= _PyArena_New();
1198 if (arena
== NULL
) {
1203 mod
= _PyParser_ASTFromFile(fp
, filename
, NULL
, start
, NULL
, NULL
,
1204 flags
, NULL
, arena
);
1212 ret
= run_mod(mod
, filename
, globals
, locals
, flags
, arena
, NULL
, 0);
1217 _PyArena_Free(arena
);
1224 PyRun_FileExFlags(FILE *fp
, const char *filename
, int start
, PyObject
*globals
,
1225 PyObject
*locals
, int closeit
, PyCompilerFlags
*flags
)
1227 PyObject
*filename_obj
= PyUnicode_DecodeFSDefault(filename
);
1228 if (filename_obj
== NULL
) {
1232 PyObject
*res
= pyrun_file(fp
, filename_obj
, start
, globals
,
1233 locals
, closeit
, flags
);
1234 Py_DECREF(filename_obj
);
1240 flush_io_stream(PyThreadState
*tstate
, PyObject
*name
)
1242 PyObject
*f
= _PySys_GetAttr(tstate
, name
);
1244 if (_PyFile_Flush(f
) < 0) {
1253 PyThreadState
*tstate
= _PyThreadState_GET();
1254 PyObject
*exc
= _PyErr_GetRaisedException(tstate
);
1255 flush_io_stream(tstate
, &_Py_ID(stderr
));
1256 flush_io_stream(tstate
, &_Py_ID(stdout
));
1257 _PyErr_SetRaisedException(tstate
, exc
);
1261 run_eval_code_obj(PyThreadState
*tstate
, PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
)
1265 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1266 * _just in case_ someone is calling into an embedded Python where they
1267 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1268 * leave config.install_signal_handlers set to 0?!?) but then later call
1269 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1270 * its interpreter exits). We don't want a previous embedded interpreter's
1271 * uncaught exception to trigger an unexplained signal exit from a future
1272 * Py_Main() based one.
1274 // XXX Isn't this dealt with by the move to _PyRuntimeState?
1275 _PyRuntime
.signals
.unhandled_keyboard_interrupt
= 0;
1277 /* Set globals['__builtins__'] if it doesn't exist */
1278 if (!globals
|| !PyDict_Check(globals
)) {
1279 PyErr_SetString(PyExc_SystemError
, "globals must be a real dict");
1282 int has_builtins
= PyDict_ContainsString(globals
, "__builtins__");
1283 if (has_builtins
< 0) {
1286 if (!has_builtins
) {
1287 if (PyDict_SetItemString(globals
, "__builtins__",
1288 tstate
->interp
->builtins
) < 0)
1294 v
= PyEval_EvalCode((PyObject
*)co
, globals
, locals
);
1295 if (!v
&& _PyErr_Occurred(tstate
) == PyExc_KeyboardInterrupt
) {
1296 _PyRuntime
.signals
.unhandled_keyboard_interrupt
= 1;
1302 run_mod(mod_ty mod
, PyObject
*filename
, PyObject
*globals
, PyObject
*locals
,
1303 PyCompilerFlags
*flags
, PyArena
*arena
, PyObject
* interactive_src
,
1304 int generate_new_source
)
1306 PyThreadState
*tstate
= _PyThreadState_GET();
1307 PyObject
* interactive_filename
= filename
;
1308 if (interactive_src
) {
1309 PyInterpreterState
*interp
= tstate
->interp
;
1310 if (generate_new_source
) {
1311 interactive_filename
= PyUnicode_FromFormat(
1312 "%U-%d", filename
, interp
->_interactive_src_count
++);
1314 Py_INCREF(interactive_filename
);
1316 if (interactive_filename
== NULL
) {
1321 PyCodeObject
*co
= _PyAST_Compile(mod
, interactive_filename
, flags
, -1, arena
);
1323 if (interactive_src
) {
1324 Py_DECREF(interactive_filename
);
1329 if (interactive_src
) {
1330 PyObject
*linecache_module
= PyImport_ImportModule("linecache");
1332 if (linecache_module
== NULL
) {
1334 Py_DECREF(interactive_filename
);
1338 PyObject
*print_tb_func
= PyObject_GetAttrString(linecache_module
, "_register_code");
1340 if (print_tb_func
== NULL
) {
1342 Py_DECREF(interactive_filename
);
1343 Py_DECREF(linecache_module
);
1347 if (!PyCallable_Check(print_tb_func
)) {
1349 Py_DECREF(interactive_filename
);
1350 Py_DECREF(linecache_module
);
1351 Py_DECREF(print_tb_func
);
1352 PyErr_SetString(PyExc_ValueError
, "linecache._register_code is not callable");
1356 PyObject
* result
= PyObject_CallFunction(
1357 print_tb_func
, "OOO",
1358 interactive_filename
,
1363 Py_DECREF(interactive_filename
);
1365 Py_DECREF(linecache_module
);
1366 Py_XDECREF(print_tb_func
);
1374 if (_PySys_Audit(tstate
, "exec", "O", co
) < 0) {
1379 PyObject
*v
= run_eval_code_obj(tstate
, co
, globals
, locals
);
1385 run_pyc_file(FILE *fp
, PyObject
*globals
, PyObject
*locals
,
1386 PyCompilerFlags
*flags
)
1388 PyThreadState
*tstate
= _PyThreadState_GET();
1392 long PyImport_GetMagicNumber(void);
1394 magic
= PyMarshal_ReadLongFromFile(fp
);
1395 if (magic
!= PyImport_GetMagicNumber()) {
1396 if (!PyErr_Occurred())
1397 PyErr_SetString(PyExc_RuntimeError
,
1398 "Bad magic number in .pyc file");
1401 /* Skip the rest of the header. */
1402 (void) PyMarshal_ReadLongFromFile(fp
);
1403 (void) PyMarshal_ReadLongFromFile(fp
);
1404 (void) PyMarshal_ReadLongFromFile(fp
);
1405 if (PyErr_Occurred()) {
1408 v
= PyMarshal_ReadLastObjectFromFile(fp
);
1409 if (v
== NULL
|| !PyCode_Check(v
)) {
1411 PyErr_SetString(PyExc_RuntimeError
,
1412 "Bad code object in .pyc file");
1416 co
= (PyCodeObject
*)v
;
1417 v
= run_eval_code_obj(tstate
, co
, globals
, locals
);
1419 flags
->cf_flags
|= (co
->co_flags
& PyCF_MASK
);
1428 Py_CompileStringObject(const char *str
, PyObject
*filename
, int start
,
1429 PyCompilerFlags
*flags
, int optimize
)
1433 PyArena
*arena
= _PyArena_New();
1437 mod
= _PyParser_ASTFromString(str
, filename
, start
, flags
, arena
);
1439 _PyArena_Free(arena
);
1442 if (flags
&& (flags
->cf_flags
& PyCF_ONLY_AST
)) {
1443 if ((flags
->cf_flags
& PyCF_OPTIMIZED_AST
) == PyCF_OPTIMIZED_AST
) {
1444 if (_PyCompile_AstOptimize(mod
, filename
, flags
, optimize
, arena
) < 0) {
1448 PyObject
*result
= PyAST_mod2obj(mod
);
1449 _PyArena_Free(arena
);
1452 co
= _PyAST_Compile(mod
, filename
, flags
, optimize
, arena
);
1453 _PyArena_Free(arena
);
1454 return (PyObject
*)co
;
1458 Py_CompileStringExFlags(const char *str
, const char *filename_str
, int start
,
1459 PyCompilerFlags
*flags
, int optimize
)
1461 PyObject
*filename
, *co
;
1462 filename
= PyUnicode_DecodeFSDefault(filename_str
);
1463 if (filename
== NULL
)
1465 co
= Py_CompileStringObject(str
, filename
, start
, flags
, optimize
);
1466 Py_DECREF(filename
);
1471 _Py_SourceAsString(PyObject
*cmd
, const char *funcname
, const char *what
, PyCompilerFlags
*cf
, PyObject
**cmd_copy
)
1478 if (PyUnicode_Check(cmd
)) {
1479 cf
->cf_flags
|= PyCF_IGNORE_COOKIE
;
1480 str
= PyUnicode_AsUTF8AndSize(cmd
, &size
);
1484 else if (PyBytes_Check(cmd
)) {
1485 str
= PyBytes_AS_STRING(cmd
);
1486 size
= PyBytes_GET_SIZE(cmd
);
1488 else if (PyByteArray_Check(cmd
)) {
1489 str
= PyByteArray_AS_STRING(cmd
);
1490 size
= PyByteArray_GET_SIZE(cmd
);
1492 else if (PyObject_GetBuffer(cmd
, &view
, PyBUF_SIMPLE
) == 0) {
1493 /* Copy to NUL-terminated buffer. */
1494 *cmd_copy
= PyBytes_FromStringAndSize(
1495 (const char *)view
.buf
, view
.len
);
1496 PyBuffer_Release(&view
);
1497 if (*cmd_copy
== NULL
) {
1500 str
= PyBytes_AS_STRING(*cmd_copy
);
1501 size
= PyBytes_GET_SIZE(*cmd_copy
);
1504 PyErr_Format(PyExc_TypeError
,
1505 "%s() arg 1 must be a %s object",
1510 if (strlen(str
) != (size_t)size
) {
1511 PyErr_SetString(PyExc_SyntaxError
,
1512 "source code string cannot contain null bytes");
1513 Py_CLEAR(*cmd_copy
);
1519 #if defined(USE_STACKCHECK)
1520 #if defined(WIN32) && defined(_MSC_VER)
1522 /* Stack checking for Microsoft C */
1528 * Return non-zero when we run out of memory on the stack; zero otherwise.
1531 PyOS_CheckStack(void)
1534 /* alloca throws a stack overflow exception if there's
1535 not enough space left on the stack */
1536 alloca(PYOS_STACK_MARGIN
* sizeof(void*));
1538 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW
?
1539 EXCEPTION_EXECUTE_HANDLER
:
1540 EXCEPTION_CONTINUE_SEARCH
) {
1541 int errcode
= _resetstkoflw();
1544 Py_FatalError("Could not reset the stack!");
1550 #endif /* WIN32 && _MSC_VER */
1552 /* Alternate implementations can be added here... */
1554 #endif /* USE_STACKCHECK */
1556 /* Deprecated C API functions still provided for binary compatibility */
1558 #undef PyRun_AnyFile
1560 PyRun_AnyFile(FILE *fp
, const char *name
)
1562 return PyRun_AnyFileExFlags(fp
, name
, 0, NULL
);
1565 #undef PyRun_AnyFileEx
1567 PyRun_AnyFileEx(FILE *fp
, const char *name
, int closeit
)
1569 return PyRun_AnyFileExFlags(fp
, name
, closeit
, NULL
);
1572 #undef PyRun_AnyFileFlags
1574 PyRun_AnyFileFlags(FILE *fp
, const char *name
, PyCompilerFlags
*flags
)
1576 return PyRun_AnyFileExFlags(fp
, name
, 0, flags
);
1580 PyAPI_FUNC(PyObject
*)
1581 PyRun_File(FILE *fp
, const char *p
, int s
, PyObject
*g
, PyObject
*l
)
1583 return PyRun_FileExFlags(fp
, p
, s
, g
, l
, 0, NULL
);
1587 PyAPI_FUNC(PyObject
*)
1588 PyRun_FileEx(FILE *fp
, const char *p
, int s
, PyObject
*g
, PyObject
*l
, int c
)
1590 return PyRun_FileExFlags(fp
, p
, s
, g
, l
, c
, NULL
);
1593 #undef PyRun_FileFlags
1594 PyAPI_FUNC(PyObject
*)
1595 PyRun_FileFlags(FILE *fp
, const char *p
, int s
, PyObject
*g
, PyObject
*l
,
1596 PyCompilerFlags
*flags
)
1598 return PyRun_FileExFlags(fp
, p
, s
, g
, l
, 0, flags
);
1601 #undef PyRun_SimpleFile
1603 PyRun_SimpleFile(FILE *f
, const char *p
)
1605 return PyRun_SimpleFileExFlags(f
, p
, 0, NULL
);
1608 #undef PyRun_SimpleFileEx
1610 PyRun_SimpleFileEx(FILE *f
, const char *p
, int c
)
1612 return PyRun_SimpleFileExFlags(f
, p
, c
, NULL
);
1617 PyAPI_FUNC(PyObject
*)
1618 PyRun_String(const char *str
, int s
, PyObject
*g
, PyObject
*l
)
1620 return PyRun_StringFlags(str
, s
, g
, l
, NULL
);
1623 #undef PyRun_SimpleString
1625 PyRun_SimpleString(const char *s
)
1627 return PyRun_SimpleStringFlags(s
, NULL
);
1630 #undef Py_CompileString
1631 PyAPI_FUNC(PyObject
*)
1632 Py_CompileString(const char *str
, const char *p
, int s
)
1634 return Py_CompileStringExFlags(str
, p
, s
, NULL
, -1);
1637 #undef Py_CompileStringFlags
1638 PyAPI_FUNC(PyObject
*)
1639 Py_CompileStringFlags(const char *str
, const char *p
, int s
,
1640 PyCompilerFlags
*flags
)
1642 return Py_CompileStringExFlags(str
, p
, s
, flags
, -1);
1645 #undef PyRun_InteractiveOne
1647 PyRun_InteractiveOne(FILE *f
, const char *p
)
1649 return PyRun_InteractiveOneFlags(f
, p
, NULL
);
1652 #undef PyRun_InteractiveLoop
1654 PyRun_InteractiveLoop(FILE *f
, const char *p
)
1656 return PyRun_InteractiveLoopFlags(f
, p
, NULL
);