• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /* Python interpreter top-level routines, including init/exit */
3 
4 #include "Python.h"
5 
6 #include "Python-ast.h"
7 #undef Yield /* undefine macro conflicting with winbase.h */
8 #include "grammar.h"
9 #include "node.h"
10 #include "token.h"
11 #include "parsetok.h"
12 #include "errcode.h"
13 #include "code.h"
14 #include "symtable.h"
15 #include "ast.h"
16 #include "marshal.h"
17 #include "osdefs.h"
18 #include <locale.h>
19 
20 #ifdef HAVE_SIGNAL_H
21 #include <signal.h>
22 #endif
23 
24 #ifdef MS_WINDOWS
25 #include "malloc.h" /* for alloca */
26 #endif
27 
28 #ifdef HAVE_LANGINFO_H
29 #include <langinfo.h>
30 #endif
31 
32 #ifdef MS_WINDOWS
33 #undef BYTE
34 #include "windows.h"
35 #endif
36 
37 _Py_IDENTIFIER(builtins);
38 _Py_IDENTIFIER(excepthook);
39 _Py_IDENTIFIER(flush);
40 _Py_IDENTIFIER(last_traceback);
41 _Py_IDENTIFIER(last_type);
42 _Py_IDENTIFIER(last_value);
43 _Py_IDENTIFIER(ps1);
44 _Py_IDENTIFIER(ps2);
45 _Py_IDENTIFIER(stdin);
46 _Py_IDENTIFIER(stdout);
47 _Py_IDENTIFIER(stderr);
48 _Py_static_string(PyId_string, "<string>");
49 
50 #ifdef __cplusplus
51 extern "C" {
52 #endif
53 
54 extern grammar _PyParser_Grammar; /* From graminit.c */
55 
56 /* Forward */
57 static void flush_io(void);
58 static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
59                           PyCompilerFlags *, PyArena *);
60 static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
61                               PyCompilerFlags *);
62 static void err_input(perrdetail *);
63 static void err_free(perrdetail *);
64 
65 /* Parse input from a file and execute it */
66 
67 int
PyRun_AnyFileExFlags(FILE * fp,const char * filename,int closeit,PyCompilerFlags * flags)68 PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
69                      PyCompilerFlags *flags)
70 {
71     if (filename == NULL)
72         filename = "???";
73     if (Py_FdIsInteractive(fp, filename)) {
74         int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
75         if (closeit)
76             fclose(fp);
77         return err;
78     }
79     else
80         return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
81 }
82 
83 int
PyRun_InteractiveLoopFlags(FILE * fp,const char * filename_str,PyCompilerFlags * flags)84 PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
85 {
86     PyObject *filename, *v;
87     int ret, err;
88     PyCompilerFlags local_flags;
89 
90     filename = PyUnicode_DecodeFSDefault(filename_str);
91     if (filename == NULL) {
92         PyErr_Print();
93         return -1;
94     }
95 
96     if (flags == NULL) {
97         flags = &local_flags;
98         local_flags.cf_flags = 0;
99     }
100     v = _PySys_GetObjectId(&PyId_ps1);
101     if (v == NULL) {
102         _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
103         Py_XDECREF(v);
104     }
105     v = _PySys_GetObjectId(&PyId_ps2);
106     if (v == NULL) {
107         _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
108         Py_XDECREF(v);
109     }
110     err = -1;
111     for (;;) {
112         ret = PyRun_InteractiveOneObject(fp, filename, flags);
113         _PY_DEBUG_PRINT_TOTAL_REFS();
114         if (ret == E_EOF) {
115             err = 0;
116             break;
117         }
118         /*
119         if (ret == E_NOMEM)
120             break;
121         */
122     }
123     Py_DECREF(filename);
124     return err;
125 }
126 
127 /* compute parser flags based on compiler flags */
PARSER_FLAGS(PyCompilerFlags * flags)128 static int PARSER_FLAGS(PyCompilerFlags *flags)
129 {
130     int parser_flags = 0;
131     if (!flags)
132         return 0;
133     if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
134         parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
135     if (flags->cf_flags & PyCF_IGNORE_COOKIE)
136         parser_flags |= PyPARSE_IGNORE_COOKIE;
137     if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
138         parser_flags |= PyPARSE_BARRY_AS_BDFL;
139     return parser_flags;
140 }
141 
142 #if 0
143 /* Keep an example of flags with future keyword support. */
144 #define PARSER_FLAGS(flags) \
145     ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
146                   PyPARSE_DONT_IMPLY_DEDENT : 0) \
147                 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
148                    PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
149 #endif
150 
151 int
PyRun_InteractiveOneObject(FILE * fp,PyObject * filename,PyCompilerFlags * flags)152 PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
153 {
154     PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
155     mod_ty mod;
156     PyArena *arena;
157     char *ps1 = "", *ps2 = "", *enc = NULL;
158     int errcode = 0;
159     _Py_IDENTIFIER(encoding);
160     _Py_IDENTIFIER(__main__);
161 
162     mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
163     if (mod_name == NULL) {
164         PyErr_Print();
165         return -1;
166     }
167 
168     if (fp == stdin) {
169         /* Fetch encoding from sys.stdin if possible. */
170         v = _PySys_GetObjectId(&PyId_stdin);
171         if (v && v != Py_None) {
172             oenc = _PyObject_GetAttrId(v, &PyId_encoding);
173             if (oenc)
174                 enc = PyUnicode_AsUTF8(oenc);
175             if (!enc)
176                 PyErr_Clear();
177         }
178     }
179     v = _PySys_GetObjectId(&PyId_ps1);
180     if (v != NULL) {
181         v = PyObject_Str(v);
182         if (v == NULL)
183             PyErr_Clear();
184         else if (PyUnicode_Check(v)) {
185             ps1 = PyUnicode_AsUTF8(v);
186             if (ps1 == NULL) {
187                 PyErr_Clear();
188                 ps1 = "";
189             }
190         }
191     }
192     w = _PySys_GetObjectId(&PyId_ps2);
193     if (w != NULL) {
194         w = PyObject_Str(w);
195         if (w == NULL)
196             PyErr_Clear();
197         else if (PyUnicode_Check(w)) {
198             ps2 = PyUnicode_AsUTF8(w);
199             if (ps2 == NULL) {
200                 PyErr_Clear();
201                 ps2 = "";
202             }
203         }
204     }
205     arena = PyArena_New();
206     if (arena == NULL) {
207         Py_XDECREF(v);
208         Py_XDECREF(w);
209         Py_XDECREF(oenc);
210         return -1;
211     }
212     mod = PyParser_ASTFromFileObject(fp, filename, enc,
213                                      Py_single_input, ps1, ps2,
214                                      flags, &errcode, arena);
215     Py_XDECREF(v);
216     Py_XDECREF(w);
217     Py_XDECREF(oenc);
218     if (mod == NULL) {
219         PyArena_Free(arena);
220         if (errcode == E_EOF) {
221             PyErr_Clear();
222             return E_EOF;
223         }
224         PyErr_Print();
225         return -1;
226     }
227     m = PyImport_AddModuleObject(mod_name);
228     if (m == NULL) {
229         PyArena_Free(arena);
230         return -1;
231     }
232     d = PyModule_GetDict(m);
233     v = run_mod(mod, filename, d, d, flags, arena);
234     PyArena_Free(arena);
235     if (v == NULL) {
236         PyErr_Print();
237         flush_io();
238         return -1;
239     }
240     Py_DECREF(v);
241     flush_io();
242     return 0;
243 }
244 
245 int
PyRun_InteractiveOneFlags(FILE * fp,const char * filename_str,PyCompilerFlags * flags)246 PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
247 {
248     PyObject *filename;
249     int res;
250 
251     filename = PyUnicode_DecodeFSDefault(filename_str);
252     if (filename == NULL) {
253         PyErr_Print();
254         return -1;
255     }
256     res = PyRun_InteractiveOneObject(fp, filename, flags);
257     Py_DECREF(filename);
258     return res;
259 }
260 
261 
262 /* Check whether a file maybe a pyc file: Look at the extension,
263    the file type, and, if we may close it, at the first few bytes. */
264 
265 static int
maybe_pyc_file(FILE * fp,const char * filename,const char * ext,int closeit)266 maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
267 {
268     if (strcmp(ext, ".pyc") == 0)
269         return 1;
270 
271     /* Only look into the file if we are allowed to close it, since
272        it then should also be seekable. */
273     if (closeit) {
274         /* Read only two bytes of the magic. If the file was opened in
275            text mode, the bytes 3 and 4 of the magic (\r\n) might not
276            be read as they are on disk. */
277         unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
278         unsigned char buf[2];
279         /* Mess:  In case of -x, the stream is NOT at its start now,
280            and ungetc() was used to push back the first newline,
281            which makes the current stream position formally undefined,
282            and a x-platform nightmare.
283            Unfortunately, we have no direct way to know whether -x
284            was specified.  So we use a terrible hack:  if the current
285            stream position is not 0, we assume -x was specified, and
286            give up.  Bug 132850 on SourceForge spells out the
287            hopelessness of trying anything else (fseek and ftell
288            don't work predictably x-platform for text-mode files).
289         */
290         int ispyc = 0;
291         if (ftell(fp) == 0) {
292             if (fread(buf, 1, 2, fp) == 2 &&
293                 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
294                 ispyc = 1;
295             rewind(fp);
296         }
297         return ispyc;
298     }
299     return 0;
300 }
301 
302 static int
set_main_loader(PyObject * d,const char * filename,const char * loader_name)303 set_main_loader(PyObject *d, const char *filename, const char *loader_name)
304 {
305     PyInterpreterState *interp;
306     PyThreadState *tstate;
307     PyObject *filename_obj, *bootstrap, *loader_type = NULL, *loader;
308     int result = 0;
309 
310     filename_obj = PyUnicode_DecodeFSDefault(filename);
311     if (filename_obj == NULL)
312         return -1;
313     /* Get current thread state and interpreter pointer */
314     tstate = PyThreadState_GET();
315     interp = tstate->interp;
316     bootstrap = PyObject_GetAttrString(interp->importlib,
317                                        "_bootstrap_external");
318     if (bootstrap != NULL) {
319         loader_type = PyObject_GetAttrString(bootstrap, loader_name);
320         Py_DECREF(bootstrap);
321     }
322     if (loader_type == NULL) {
323         Py_DECREF(filename_obj);
324         return -1;
325     }
326     loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
327     Py_DECREF(loader_type);
328     if (loader == NULL) {
329         return -1;
330     }
331     if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
332         result = -1;
333     }
334     Py_DECREF(loader);
335     return result;
336 }
337 
338 int
PyRun_SimpleFileExFlags(FILE * fp,const char * filename,int closeit,PyCompilerFlags * flags)339 PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
340                         PyCompilerFlags *flags)
341 {
342     PyObject *m, *d, *v;
343     const char *ext;
344     int set_file_name = 0, ret = -1;
345     size_t len;
346 
347     m = PyImport_AddModule("__main__");
348     if (m == NULL)
349         return -1;
350     Py_INCREF(m);
351     d = PyModule_GetDict(m);
352     if (PyDict_GetItemString(d, "__file__") == NULL) {
353         PyObject *f;
354         f = PyUnicode_DecodeFSDefault(filename);
355         if (f == NULL)
356             goto done;
357         if (PyDict_SetItemString(d, "__file__", f) < 0) {
358             Py_DECREF(f);
359             goto done;
360         }
361         if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
362             Py_DECREF(f);
363             goto done;
364         }
365         set_file_name = 1;
366         Py_DECREF(f);
367     }
368     len = strlen(filename);
369     ext = filename + len - (len > 4 ? 4 : 0);
370     if (maybe_pyc_file(fp, filename, ext, closeit)) {
371         FILE *pyc_fp;
372         /* Try to run a pyc file. First, re-open in binary */
373         if (closeit)
374             fclose(fp);
375         if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
376             fprintf(stderr, "python: Can't reopen .pyc file\n");
377             goto done;
378         }
379 
380         if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
381             fprintf(stderr, "python: failed to set __main__.__loader__\n");
382             ret = -1;
383             fclose(pyc_fp);
384             goto done;
385         }
386         v = run_pyc_file(pyc_fp, filename, d, d, flags);
387         fclose(pyc_fp);
388     } else {
389         /* When running from stdin, leave __main__.__loader__ alone */
390         if (strcmp(filename, "<stdin>") != 0 &&
391             set_main_loader(d, filename, "SourceFileLoader") < 0) {
392             fprintf(stderr, "python: failed to set __main__.__loader__\n");
393             ret = -1;
394             goto done;
395         }
396         v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
397                               closeit, flags);
398     }
399     flush_io();
400     if (v == NULL) {
401         PyErr_Print();
402         goto done;
403     }
404     Py_DECREF(v);
405     ret = 0;
406   done:
407     if (set_file_name && PyDict_DelItemString(d, "__file__"))
408         PyErr_Clear();
409     Py_DECREF(m);
410     return ret;
411 }
412 
413 int
PyRun_SimpleStringFlags(const char * command,PyCompilerFlags * flags)414 PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
415 {
416     PyObject *m, *d, *v;
417     m = PyImport_AddModule("__main__");
418     if (m == NULL)
419         return -1;
420     d = PyModule_GetDict(m);
421     v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
422     if (v == NULL) {
423         PyErr_Print();
424         return -1;
425     }
426     Py_DECREF(v);
427     return 0;
428 }
429 
430 static int
parse_syntax_error(PyObject * err,PyObject ** message,PyObject ** filename,int * lineno,int * offset,PyObject ** text)431 parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
432                    int *lineno, int *offset, PyObject **text)
433 {
434     int hold;
435     PyObject *v;
436     _Py_IDENTIFIER(msg);
437     _Py_IDENTIFIER(filename);
438     _Py_IDENTIFIER(lineno);
439     _Py_IDENTIFIER(offset);
440     _Py_IDENTIFIER(text);
441 
442     *message = NULL;
443     *filename = NULL;
444 
445     /* new style errors.  `err' is an instance */
446     *message = _PyObject_GetAttrId(err, &PyId_msg);
447     if (!*message)
448         goto finally;
449 
450     v = _PyObject_GetAttrId(err, &PyId_filename);
451     if (!v)
452         goto finally;
453     if (v == Py_None) {
454         Py_DECREF(v);
455         *filename = _PyUnicode_FromId(&PyId_string);
456         if (*filename == NULL)
457             goto finally;
458         Py_INCREF(*filename);
459     }
460     else {
461         *filename = v;
462     }
463 
464     v = _PyObject_GetAttrId(err, &PyId_lineno);
465     if (!v)
466         goto finally;
467     hold = _PyLong_AsInt(v);
468     Py_DECREF(v);
469     if (hold < 0 && PyErr_Occurred())
470         goto finally;
471     *lineno = hold;
472 
473     v = _PyObject_GetAttrId(err, &PyId_offset);
474     if (!v)
475         goto finally;
476     if (v == Py_None) {
477         *offset = -1;
478         Py_DECREF(v);
479     } else {
480         hold = _PyLong_AsInt(v);
481         Py_DECREF(v);
482         if (hold < 0 && PyErr_Occurred())
483             goto finally;
484         *offset = hold;
485     }
486 
487     v = _PyObject_GetAttrId(err, &PyId_text);
488     if (!v)
489         goto finally;
490     if (v == Py_None) {
491         Py_DECREF(v);
492         *text = NULL;
493     }
494     else {
495         *text = v;
496     }
497     return 1;
498 
499 finally:
500     Py_XDECREF(*message);
501     Py_XDECREF(*filename);
502     return 0;
503 }
504 
505 void
PyErr_Print(void)506 PyErr_Print(void)
507 {
508     PyErr_PrintEx(1);
509 }
510 
511 static void
print_error_text(PyObject * f,int offset,PyObject * text_obj)512 print_error_text(PyObject *f, int offset, PyObject *text_obj)
513 {
514     char *text;
515     char *nl;
516 
517     text = PyUnicode_AsUTF8(text_obj);
518     if (text == NULL)
519         return;
520 
521     if (offset >= 0) {
522         if (offset > 0 && (size_t)offset == strlen(text) && text[offset - 1] == '\n')
523             offset--;
524         for (;;) {
525             nl = strchr(text, '\n');
526             if (nl == NULL || nl-text >= offset)
527                 break;
528             offset -= (int)(nl+1-text);
529             text = nl+1;
530         }
531         while (*text == ' ' || *text == '\t' || *text == '\f') {
532             text++;
533             offset--;
534         }
535     }
536     PyFile_WriteString("    ", f);
537     PyFile_WriteString(text, f);
538     if (*text == '\0' || text[strlen(text)-1] != '\n')
539         PyFile_WriteString("\n", f);
540     if (offset == -1)
541         return;
542     PyFile_WriteString("    ", f);
543     while (--offset > 0)
544         PyFile_WriteString(" ", f);
545     PyFile_WriteString("^\n", f);
546 }
547 
548 static void
handle_system_exit(void)549 handle_system_exit(void)
550 {
551     PyObject *exception, *value, *tb;
552     int exitcode = 0;
553 
554     if (Py_InspectFlag)
555         /* Don't exit if -i flag was given. This flag is set to 0
556          * when entering interactive mode for inspecting. */
557         return;
558 
559     PyErr_Fetch(&exception, &value, &tb);
560     fflush(stdout);
561     if (value == NULL || value == Py_None)
562         goto done;
563     if (PyExceptionInstance_Check(value)) {
564         /* The error code should be in the `code' attribute. */
565         _Py_IDENTIFIER(code);
566         PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
567         if (code) {
568             Py_DECREF(value);
569             value = code;
570             if (value == Py_None)
571                 goto done;
572         }
573         /* If we failed to dig out the 'code' attribute,
574            just let the else clause below print the error. */
575     }
576     if (PyLong_Check(value))
577         exitcode = (int)PyLong_AsLong(value);
578     else {
579         PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
580         /* We clear the exception here to avoid triggering the assertion
581          * in PyObject_Str that ensures it won't silently lose exception
582          * details.
583          */
584         PyErr_Clear();
585         if (sys_stderr != NULL && sys_stderr != Py_None) {
586             PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
587         } else {
588             PyObject_Print(value, stderr, Py_PRINT_RAW);
589             fflush(stderr);
590         }
591         PySys_WriteStderr("\n");
592         exitcode = 1;
593     }
594  done:
595     /* Restore and clear the exception info, in order to properly decref
596      * the exception, value, and traceback.      If we just exit instead,
597      * these leak, which confuses PYTHONDUMPREFS output, and may prevent
598      * some finalizers from running.
599      */
600     PyErr_Restore(exception, value, tb);
601     PyErr_Clear();
602     Py_Exit(exitcode);
603     /* NOTREACHED */
604 }
605 
606 void
PyErr_PrintEx(int set_sys_last_vars)607 PyErr_PrintEx(int set_sys_last_vars)
608 {
609     PyObject *exception, *v, *tb, *hook;
610 
611     if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
612         handle_system_exit();
613     }
614     PyErr_Fetch(&exception, &v, &tb);
615     if (exception == NULL)
616         return;
617     PyErr_NormalizeException(&exception, &v, &tb);
618     if (tb == NULL) {
619         tb = Py_None;
620         Py_INCREF(tb);
621     }
622     PyException_SetTraceback(v, tb);
623     if (exception == NULL)
624         return;
625     /* Now we know v != NULL too */
626     if (set_sys_last_vars) {
627         _PySys_SetObjectId(&PyId_last_type, exception);
628         _PySys_SetObjectId(&PyId_last_value, v);
629         _PySys_SetObjectId(&PyId_last_traceback, tb);
630     }
631     hook = _PySys_GetObjectId(&PyId_excepthook);
632     if (hook) {
633         PyObject* stack[3];
634         PyObject *result;
635 
636         stack[0] = exception;
637         stack[1] = v;
638         stack[2] = tb;
639         result = _PyObject_FastCall(hook, stack, 3);
640         if (result == NULL) {
641             PyObject *exception2, *v2, *tb2;
642             if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
643                 handle_system_exit();
644             }
645             PyErr_Fetch(&exception2, &v2, &tb2);
646             PyErr_NormalizeException(&exception2, &v2, &tb2);
647             /* It should not be possible for exception2 or v2
648                to be NULL. However PyErr_Display() can't
649                tolerate NULLs, so just be safe. */
650             if (exception2 == NULL) {
651                 exception2 = Py_None;
652                 Py_INCREF(exception2);
653             }
654             if (v2 == NULL) {
655                 v2 = Py_None;
656                 Py_INCREF(v2);
657             }
658             fflush(stdout);
659             PySys_WriteStderr("Error in sys.excepthook:\n");
660             PyErr_Display(exception2, v2, tb2);
661             PySys_WriteStderr("\nOriginal exception was:\n");
662             PyErr_Display(exception, v, tb);
663             Py_DECREF(exception2);
664             Py_DECREF(v2);
665             Py_XDECREF(tb2);
666         }
667         Py_XDECREF(result);
668     } else {
669         PySys_WriteStderr("sys.excepthook is missing\n");
670         PyErr_Display(exception, v, tb);
671     }
672     Py_XDECREF(exception);
673     Py_XDECREF(v);
674     Py_XDECREF(tb);
675 }
676 
677 static void
print_exception(PyObject * f,PyObject * value)678 print_exception(PyObject *f, PyObject *value)
679 {
680     int err = 0;
681     PyObject *type, *tb;
682     _Py_IDENTIFIER(print_file_and_line);
683 
684     if (!PyExceptionInstance_Check(value)) {
685         err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
686         err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
687         err += PyFile_WriteString(" found\n", f);
688         if (err)
689             PyErr_Clear();
690         return;
691     }
692 
693     Py_INCREF(value);
694     fflush(stdout);
695     type = (PyObject *) Py_TYPE(value);
696     tb = PyException_GetTraceback(value);
697     if (tb && tb != Py_None)
698         err = PyTraceBack_Print(tb, f);
699     if (err == 0 &&
700         _PyObject_HasAttrId(value, &PyId_print_file_and_line))
701     {
702         PyObject *message, *filename, *text;
703         int lineno, offset;
704         if (!parse_syntax_error(value, &message, &filename,
705                                 &lineno, &offset, &text))
706             PyErr_Clear();
707         else {
708             PyObject *line;
709 
710             Py_DECREF(value);
711             value = message;
712 
713             line = PyUnicode_FromFormat("  File \"%U\", line %d\n",
714                                           filename, lineno);
715             Py_DECREF(filename);
716             if (line != NULL) {
717                 PyFile_WriteObject(line, f, Py_PRINT_RAW);
718                 Py_DECREF(line);
719             }
720 
721             if (text != NULL) {
722                 print_error_text(f, offset, text);
723                 Py_DECREF(text);
724             }
725 
726             /* Can't be bothered to check all those
727                PyFile_WriteString() calls */
728             if (PyErr_Occurred())
729                 err = -1;
730         }
731     }
732     if (err) {
733         /* Don't do anything else */
734     }
735     else {
736         PyObject* moduleName;
737         char* className;
738         _Py_IDENTIFIER(__module__);
739         assert(PyExceptionClass_Check(type));
740         className = PyExceptionClass_Name(type);
741         if (className != NULL) {
742             char *dot = strrchr(className, '.');
743             if (dot != NULL)
744                 className = dot+1;
745         }
746 
747         moduleName = _PyObject_GetAttrId(type, &PyId___module__);
748         if (moduleName == NULL || !PyUnicode_Check(moduleName))
749         {
750             Py_XDECREF(moduleName);
751             err = PyFile_WriteString("<unknown>", f);
752         }
753         else {
754             if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
755             {
756                 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
757                 err += PyFile_WriteString(".", f);
758             }
759             Py_DECREF(moduleName);
760         }
761         if (err == 0) {
762             if (className == NULL)
763                       err = PyFile_WriteString("<unknown>", f);
764             else
765                       err = PyFile_WriteString(className, f);
766         }
767     }
768     if (err == 0 && (value != Py_None)) {
769         PyObject *s = PyObject_Str(value);
770         /* only print colon if the str() of the
771            object is not the empty string
772         */
773         if (s == NULL) {
774             PyErr_Clear();
775             err = -1;
776             PyFile_WriteString(": <exception str() failed>", f);
777         }
778         else if (!PyUnicode_Check(s) ||
779             PyUnicode_GetLength(s) != 0)
780             err = PyFile_WriteString(": ", f);
781         if (err == 0)
782           err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
783         Py_XDECREF(s);
784     }
785     /* try to write a newline in any case */
786     if (err < 0) {
787         PyErr_Clear();
788     }
789     err += PyFile_WriteString("\n", f);
790     Py_XDECREF(tb);
791     Py_DECREF(value);
792     /* If an error happened here, don't show it.
793        XXX This is wrong, but too many callers rely on this behavior. */
794     if (err != 0)
795         PyErr_Clear();
796 }
797 
798 static const char cause_message[] =
799     "\nThe above exception was the direct cause "
800     "of the following exception:\n\n";
801 
802 static const char context_message[] =
803     "\nDuring handling of the above exception, "
804     "another exception occurred:\n\n";
805 
806 static void
print_exception_recursive(PyObject * f,PyObject * value,PyObject * seen)807 print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
808 {
809     int err = 0, res;
810     PyObject *cause, *context;
811 
812     if (seen != NULL) {
813         /* Exception chaining */
814         if (PySet_Add(seen, value) == -1)
815             PyErr_Clear();
816         else if (PyExceptionInstance_Check(value)) {
817             cause = PyException_GetCause(value);
818             context = PyException_GetContext(value);
819             if (cause) {
820                 res = PySet_Contains(seen, cause);
821                 if (res == -1)
822                     PyErr_Clear();
823                 if (res == 0) {
824                     print_exception_recursive(
825                         f, cause, seen);
826                     err |= PyFile_WriteString(
827                         cause_message, f);
828                 }
829             }
830             else if (context &&
831                 !((PyBaseExceptionObject *)value)->suppress_context) {
832                 res = PySet_Contains(seen, context);
833                 if (res == -1)
834                     PyErr_Clear();
835                 if (res == 0) {
836                     print_exception_recursive(
837                         f, context, seen);
838                     err |= PyFile_WriteString(
839                         context_message, f);
840                 }
841             }
842             Py_XDECREF(context);
843             Py_XDECREF(cause);
844         }
845     }
846     print_exception(f, value);
847     if (err != 0)
848         PyErr_Clear();
849 }
850 
851 void
PyErr_Display(PyObject * exception,PyObject * value,PyObject * tb)852 PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
853 {
854     PyObject *seen;
855     PyObject *f = _PySys_GetObjectId(&PyId_stderr);
856     if (PyExceptionInstance_Check(value)
857         && tb != NULL && PyTraceBack_Check(tb)) {
858         /* Put the traceback on the exception, otherwise it won't get
859            displayed.  See issue #18776. */
860         PyObject *cur_tb = PyException_GetTraceback(value);
861         if (cur_tb == NULL)
862             PyException_SetTraceback(value, tb);
863         else
864             Py_DECREF(cur_tb);
865     }
866     if (f == Py_None) {
867         /* pass */
868     }
869     else if (f == NULL) {
870         _PyObject_Dump(value);
871         fprintf(stderr, "lost sys.stderr\n");
872     }
873     else {
874         /* We choose to ignore seen being possibly NULL, and report
875            at least the main exception (it could be a MemoryError).
876         */
877         seen = PySet_New(NULL);
878         if (seen == NULL)
879             PyErr_Clear();
880         print_exception_recursive(f, value, seen);
881         Py_XDECREF(seen);
882     }
883 }
884 
885 PyObject *
PyRun_StringFlags(const char * str,int start,PyObject * globals,PyObject * locals,PyCompilerFlags * flags)886 PyRun_StringFlags(const char *str, int start, PyObject *globals,
887                   PyObject *locals, PyCompilerFlags *flags)
888 {
889     PyObject *ret = NULL;
890     mod_ty mod;
891     PyArena *arena;
892     PyObject *filename;
893 
894     filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
895     if (filename == NULL)
896         return NULL;
897 
898     arena = PyArena_New();
899     if (arena == NULL)
900         return NULL;
901 
902     mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
903     if (mod != NULL)
904         ret = run_mod(mod, filename, globals, locals, flags, arena);
905     PyArena_Free(arena);
906     return ret;
907 }
908 
909 PyObject *
PyRun_FileExFlags(FILE * fp,const char * filename_str,int start,PyObject * globals,PyObject * locals,int closeit,PyCompilerFlags * flags)910 PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
911                   PyObject *locals, int closeit, PyCompilerFlags *flags)
912 {
913     PyObject *ret = NULL;
914     mod_ty mod;
915     PyArena *arena = NULL;
916     PyObject *filename;
917 
918     filename = PyUnicode_DecodeFSDefault(filename_str);
919     if (filename == NULL)
920         goto exit;
921 
922     arena = PyArena_New();
923     if (arena == NULL)
924         goto exit;
925 
926     mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
927                                      flags, NULL, arena);
928     if (closeit)
929         fclose(fp);
930     if (mod == NULL) {
931         goto exit;
932     }
933     ret = run_mod(mod, filename, globals, locals, flags, arena);
934 
935 exit:
936     Py_XDECREF(filename);
937     if (arena != NULL)
938         PyArena_Free(arena);
939     return ret;
940 }
941 
942 static void
flush_io(void)943 flush_io(void)
944 {
945     PyObject *f, *r;
946     PyObject *type, *value, *traceback;
947 
948     /* Save the current exception */
949     PyErr_Fetch(&type, &value, &traceback);
950 
951     f = _PySys_GetObjectId(&PyId_stderr);
952     if (f != NULL) {
953         r = _PyObject_CallMethodId(f, &PyId_flush, NULL);
954         if (r)
955             Py_DECREF(r);
956         else
957             PyErr_Clear();
958     }
959     f = _PySys_GetObjectId(&PyId_stdout);
960     if (f != NULL) {
961         r = _PyObject_CallMethodId(f, &PyId_flush, NULL);
962         if (r)
963             Py_DECREF(r);
964         else
965             PyErr_Clear();
966     }
967 
968     PyErr_Restore(type, value, traceback);
969 }
970 
971 static PyObject *
run_mod(mod_ty mod,PyObject * filename,PyObject * globals,PyObject * locals,PyCompilerFlags * flags,PyArena * arena)972 run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
973             PyCompilerFlags *flags, PyArena *arena)
974 {
975     PyCodeObject *co;
976     PyObject *v;
977     co = PyAST_CompileObject(mod, filename, flags, -1, arena);
978     if (co == NULL)
979         return NULL;
980     v = PyEval_EvalCode((PyObject*)co, globals, locals);
981     Py_DECREF(co);
982     return v;
983 }
984 
985 static PyObject *
run_pyc_file(FILE * fp,const char * filename,PyObject * globals,PyObject * locals,PyCompilerFlags * flags)986 run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
987              PyObject *locals, PyCompilerFlags *flags)
988 {
989     PyCodeObject *co;
990     PyObject *v;
991     long magic;
992     long PyImport_GetMagicNumber(void);
993 
994     magic = PyMarshal_ReadLongFromFile(fp);
995     if (magic != PyImport_GetMagicNumber()) {
996         if (!PyErr_Occurred())
997             PyErr_SetString(PyExc_RuntimeError,
998                        "Bad magic number in .pyc file");
999         return NULL;
1000     }
1001     /* Skip mtime and size */
1002     (void) PyMarshal_ReadLongFromFile(fp);
1003     (void) PyMarshal_ReadLongFromFile(fp);
1004     if (PyErr_Occurred())
1005         return NULL;
1006 
1007     v = PyMarshal_ReadLastObjectFromFile(fp);
1008     if (v == NULL || !PyCode_Check(v)) {
1009         Py_XDECREF(v);
1010         PyErr_SetString(PyExc_RuntimeError,
1011                    "Bad code object in .pyc file");
1012         return NULL;
1013     }
1014     co = (PyCodeObject *)v;
1015     v = PyEval_EvalCode((PyObject*)co, globals, locals);
1016     if (v && flags)
1017         flags->cf_flags |= (co->co_flags & PyCF_MASK);
1018     Py_DECREF(co);
1019     return v;
1020 }
1021 
1022 PyObject *
Py_CompileStringObject(const char * str,PyObject * filename,int start,PyCompilerFlags * flags,int optimize)1023 Py_CompileStringObject(const char *str, PyObject *filename, int start,
1024                        PyCompilerFlags *flags, int optimize)
1025 {
1026     PyCodeObject *co;
1027     mod_ty mod;
1028     PyArena *arena = PyArena_New();
1029     if (arena == NULL)
1030         return NULL;
1031 
1032     mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
1033     if (mod == NULL) {
1034         PyArena_Free(arena);
1035         return NULL;
1036     }
1037     if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1038         PyObject *result = PyAST_mod2obj(mod);
1039         PyArena_Free(arena);
1040         return result;
1041     }
1042     co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
1043     PyArena_Free(arena);
1044     return (PyObject *)co;
1045 }
1046 
1047 PyObject *
Py_CompileStringExFlags(const char * str,const char * filename_str,int start,PyCompilerFlags * flags,int optimize)1048 Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1049                         PyCompilerFlags *flags, int optimize)
1050 {
1051     PyObject *filename, *co;
1052     filename = PyUnicode_DecodeFSDefault(filename_str);
1053     if (filename == NULL)
1054         return NULL;
1055     co = Py_CompileStringObject(str, filename, start, flags, optimize);
1056     Py_DECREF(filename);
1057     return co;
1058 }
1059 
1060 /* For use in Py_LIMITED_API */
1061 #undef Py_CompileString
1062 PyObject *
PyCompileString(const char * str,const char * filename,int start)1063 PyCompileString(const char *str, const char *filename, int start)
1064 {
1065     return Py_CompileStringFlags(str, filename, start, NULL);
1066 }
1067 
1068 struct symtable *
Py_SymtableStringObject(const char * str,PyObject * filename,int start)1069 Py_SymtableStringObject(const char *str, PyObject *filename, int start)
1070 {
1071     struct symtable *st;
1072     mod_ty mod;
1073     PyCompilerFlags flags;
1074     PyArena *arena;
1075 
1076     arena = PyArena_New();
1077     if (arena == NULL)
1078         return NULL;
1079 
1080     flags.cf_flags = 0;
1081     mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
1082     if (mod == NULL) {
1083         PyArena_Free(arena);
1084         return NULL;
1085     }
1086     st = PySymtable_BuildObject(mod, filename, 0);
1087     PyArena_Free(arena);
1088     return st;
1089 }
1090 
1091 struct symtable *
Py_SymtableString(const char * str,const char * filename_str,int start)1092 Py_SymtableString(const char *str, const char *filename_str, int start)
1093 {
1094     PyObject *filename;
1095     struct symtable *st;
1096 
1097     filename = PyUnicode_DecodeFSDefault(filename_str);
1098     if (filename == NULL)
1099         return NULL;
1100     st = Py_SymtableStringObject(str, filename, start);
1101     Py_DECREF(filename);
1102     return st;
1103 }
1104 
1105 /* Preferred access to parser is through AST. */
1106 mod_ty
PyParser_ASTFromStringObject(const char * s,PyObject * filename,int start,PyCompilerFlags * flags,PyArena * arena)1107 PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
1108                              PyCompilerFlags *flags, PyArena *arena)
1109 {
1110     mod_ty mod;
1111     PyCompilerFlags localflags;
1112     perrdetail err;
1113     int iflags = PARSER_FLAGS(flags);
1114 
1115     node *n = PyParser_ParseStringObject(s, filename,
1116                                          &_PyParser_Grammar, start, &err,
1117                                          &iflags);
1118     if (flags == NULL) {
1119         localflags.cf_flags = 0;
1120         flags = &localflags;
1121     }
1122     if (n) {
1123         flags->cf_flags |= iflags & PyCF_MASK;
1124         mod = PyAST_FromNodeObject(n, flags, filename, arena);
1125         PyNode_Free(n);
1126     }
1127     else {
1128         err_input(&err);
1129         mod = NULL;
1130     }
1131     err_free(&err);
1132     return mod;
1133 }
1134 
1135 mod_ty
PyParser_ASTFromString(const char * s,const char * filename_str,int start,PyCompilerFlags * flags,PyArena * arena)1136 PyParser_ASTFromString(const char *s, const char *filename_str, int start,
1137                        PyCompilerFlags *flags, PyArena *arena)
1138 {
1139     PyObject *filename;
1140     mod_ty mod;
1141     filename = PyUnicode_DecodeFSDefault(filename_str);
1142     if (filename == NULL)
1143         return NULL;
1144     mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
1145     Py_DECREF(filename);
1146     return mod;
1147 }
1148 
1149 mod_ty
PyParser_ASTFromFileObject(FILE * fp,PyObject * filename,const char * enc,int start,const char * ps1,const char * ps2,PyCompilerFlags * flags,int * errcode,PyArena * arena)1150 PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
1151                            int start, const char *ps1,
1152                            const char *ps2, PyCompilerFlags *flags, int *errcode,
1153                            PyArena *arena)
1154 {
1155     mod_ty mod;
1156     PyCompilerFlags localflags;
1157     perrdetail err;
1158     int iflags = PARSER_FLAGS(flags);
1159 
1160     node *n = PyParser_ParseFileObject(fp, filename, enc,
1161                                        &_PyParser_Grammar,
1162                                        start, ps1, ps2, &err, &iflags);
1163     if (flags == NULL) {
1164         localflags.cf_flags = 0;
1165         flags = &localflags;
1166     }
1167     if (n) {
1168         flags->cf_flags |= iflags & PyCF_MASK;
1169         mod = PyAST_FromNodeObject(n, flags, filename, arena);
1170         PyNode_Free(n);
1171     }
1172     else {
1173         err_input(&err);
1174         if (errcode)
1175             *errcode = err.error;
1176         mod = NULL;
1177     }
1178     err_free(&err);
1179     return mod;
1180 }
1181 
1182 mod_ty
PyParser_ASTFromFile(FILE * fp,const char * filename_str,const char * enc,int start,const char * ps1,const char * ps2,PyCompilerFlags * flags,int * errcode,PyArena * arena)1183 PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
1184                      int start, const char *ps1,
1185                      const char *ps2, PyCompilerFlags *flags, int *errcode,
1186                      PyArena *arena)
1187 {
1188     mod_ty mod;
1189     PyObject *filename;
1190     filename = PyUnicode_DecodeFSDefault(filename_str);
1191     if (filename == NULL)
1192         return NULL;
1193     mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
1194                                      flags, errcode, arena);
1195     Py_DECREF(filename);
1196     return mod;
1197 }
1198 
1199 /* Simplified interface to parsefile -- return node or set exception */
1200 
1201 node *
PyParser_SimpleParseFileFlags(FILE * fp,const char * filename,int start,int flags)1202 PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
1203 {
1204     perrdetail err;
1205     node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1206                                       &_PyParser_Grammar,
1207                                       start, NULL, NULL, &err, flags);
1208     if (n == NULL)
1209         err_input(&err);
1210     err_free(&err);
1211 
1212     return n;
1213 }
1214 
1215 /* Simplified interface to parsestring -- return node or set exception */
1216 
1217 node *
PyParser_SimpleParseStringFlags(const char * str,int start,int flags)1218 PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
1219 {
1220     perrdetail err;
1221     node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1222                                         start, &err, flags);
1223     if (n == NULL)
1224         err_input(&err);
1225     err_free(&err);
1226     return n;
1227 }
1228 
1229 node *
PyParser_SimpleParseStringFlagsFilename(const char * str,const char * filename,int start,int flags)1230 PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
1231                                         int start, int flags)
1232 {
1233     perrdetail err;
1234     node *n = PyParser_ParseStringFlagsFilename(str, filename,
1235                             &_PyParser_Grammar, start, &err, flags);
1236     if (n == NULL)
1237         err_input(&err);
1238     err_free(&err);
1239     return n;
1240 }
1241 
1242 node *
PyParser_SimpleParseStringFilename(const char * str,const char * filename,int start)1243 PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
1244 {
1245     return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
1246 }
1247 
1248 /* May want to move a more generalized form of this to parsetok.c or
1249    even parser modules. */
1250 
1251 void
PyParser_ClearError(perrdetail * err)1252 PyParser_ClearError(perrdetail *err)
1253 {
1254     err_free(err);
1255 }
1256 
1257 void
PyParser_SetError(perrdetail * err)1258 PyParser_SetError(perrdetail *err)
1259 {
1260     err_input(err);
1261 }
1262 
1263 static void
err_free(perrdetail * err)1264 err_free(perrdetail *err)
1265 {
1266     Py_CLEAR(err->filename);
1267 }
1268 
1269 /* Set the error appropriate to the given input error code (see errcode.h) */
1270 
1271 static void
err_input(perrdetail * err)1272 err_input(perrdetail *err)
1273 {
1274     PyObject *v, *w, *errtype, *errtext;
1275     PyObject *msg_obj = NULL;
1276     char *msg = NULL;
1277     int offset = err->offset;
1278 
1279     errtype = PyExc_SyntaxError;
1280     switch (err->error) {
1281     case E_ERROR:
1282         return;
1283     case E_SYNTAX:
1284         errtype = PyExc_IndentationError;
1285         if (err->expected == INDENT)
1286             msg = "expected an indented block";
1287         else if (err->token == INDENT)
1288             msg = "unexpected indent";
1289         else if (err->token == DEDENT)
1290             msg = "unexpected unindent";
1291         else {
1292             errtype = PyExc_SyntaxError;
1293             msg = "invalid syntax";
1294         }
1295         break;
1296     case E_TOKEN:
1297         msg = "invalid token";
1298         break;
1299     case E_EOFS:
1300         msg = "EOF while scanning triple-quoted string literal";
1301         break;
1302     case E_EOLS:
1303         msg = "EOL while scanning string literal";
1304         break;
1305     case E_INTR:
1306         if (!PyErr_Occurred())
1307             PyErr_SetNone(PyExc_KeyboardInterrupt);
1308         goto cleanup;
1309     case E_NOMEM:
1310         PyErr_NoMemory();
1311         goto cleanup;
1312     case E_EOF:
1313         msg = "unexpected EOF while parsing";
1314         break;
1315     case E_TABSPACE:
1316         errtype = PyExc_TabError;
1317         msg = "inconsistent use of tabs and spaces in indentation";
1318         break;
1319     case E_OVERFLOW:
1320         msg = "expression too long";
1321         break;
1322     case E_DEDENT:
1323         errtype = PyExc_IndentationError;
1324         msg = "unindent does not match any outer indentation level";
1325         break;
1326     case E_TOODEEP:
1327         errtype = PyExc_IndentationError;
1328         msg = "too many levels of indentation";
1329         break;
1330     case E_DECODE: {
1331         PyObject *type, *value, *tb;
1332         PyErr_Fetch(&type, &value, &tb);
1333         msg = "unknown decode error";
1334         if (value != NULL)
1335             msg_obj = PyObject_Str(value);
1336         Py_XDECREF(type);
1337         Py_XDECREF(value);
1338         Py_XDECREF(tb);
1339         break;
1340     }
1341     case E_LINECONT:
1342         msg = "unexpected character after line continuation character";
1343         break;
1344 
1345     case E_IDENTIFIER:
1346         msg = "invalid character in identifier";
1347         break;
1348     case E_BADSINGLE:
1349         msg = "multiple statements found while compiling a single statement";
1350         break;
1351     default:
1352         fprintf(stderr, "error=%d\n", err->error);
1353         msg = "unknown parsing error";
1354         break;
1355     }
1356     /* err->text may not be UTF-8 in case of decoding errors.
1357        Explicitly convert to an object. */
1358     if (!err->text) {
1359         errtext = Py_None;
1360         Py_INCREF(Py_None);
1361     } else {
1362         errtext = PyUnicode_DecodeUTF8(err->text, err->offset,
1363                                        "replace");
1364         if (errtext != NULL) {
1365             Py_ssize_t len = strlen(err->text);
1366             offset = (int)PyUnicode_GET_LENGTH(errtext);
1367             if (len != err->offset) {
1368                 Py_DECREF(errtext);
1369                 errtext = PyUnicode_DecodeUTF8(err->text, len,
1370                                                "replace");
1371             }
1372         }
1373     }
1374     v = Py_BuildValue("(OiiN)", err->filename,
1375                       err->lineno, offset, errtext);
1376     if (v != NULL) {
1377         if (msg_obj)
1378             w = Py_BuildValue("(OO)", msg_obj, v);
1379         else
1380             w = Py_BuildValue("(sO)", msg, v);
1381     } else
1382         w = NULL;
1383     Py_XDECREF(v);
1384     PyErr_SetObject(errtype, w);
1385     Py_XDECREF(w);
1386 cleanup:
1387     Py_XDECREF(msg_obj);
1388     if (err->text != NULL) {
1389         PyObject_FREE(err->text);
1390         err->text = NULL;
1391     }
1392 }
1393 
1394 
1395 #if defined(USE_STACKCHECK)
1396 #if defined(WIN32) && defined(_MSC_VER)
1397 
1398 /* Stack checking for Microsoft C */
1399 
1400 #include <malloc.h>
1401 #include <excpt.h>
1402 
1403 /*
1404  * Return non-zero when we run out of memory on the stack; zero otherwise.
1405  */
1406 int
PyOS_CheckStack(void)1407 PyOS_CheckStack(void)
1408 {
1409     __try {
1410         /* alloca throws a stack overflow exception if there's
1411            not enough space left on the stack */
1412         alloca(PYOS_STACK_MARGIN * sizeof(void*));
1413         return 0;
1414     } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1415                     EXCEPTION_EXECUTE_HANDLER :
1416             EXCEPTION_CONTINUE_SEARCH) {
1417         int errcode = _resetstkoflw();
1418         if (errcode == 0)
1419         {
1420             Py_FatalError("Could not reset the stack!");
1421         }
1422     }
1423     return 1;
1424 }
1425 
1426 #endif /* WIN32 && _MSC_VER */
1427 
1428 /* Alternate implementations can be added here... */
1429 
1430 #endif /* USE_STACKCHECK */
1431 
1432 /* Deprecated C API functions still provided for binary compatibility */
1433 
1434 #undef PyParser_SimpleParseFile
1435 PyAPI_FUNC(node *)
PyParser_SimpleParseFile(FILE * fp,const char * filename,int start)1436 PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1437 {
1438     return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1439 }
1440 
1441 #undef PyParser_SimpleParseString
1442 PyAPI_FUNC(node *)
PyParser_SimpleParseString(const char * str,int start)1443 PyParser_SimpleParseString(const char *str, int start)
1444 {
1445     return PyParser_SimpleParseStringFlags(str, start, 0);
1446 }
1447 
1448 #undef PyRun_AnyFile
1449 PyAPI_FUNC(int)
PyRun_AnyFile(FILE * fp,const char * name)1450 PyRun_AnyFile(FILE *fp, const char *name)
1451 {
1452     return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1453 }
1454 
1455 #undef PyRun_AnyFileEx
1456 PyAPI_FUNC(int)
PyRun_AnyFileEx(FILE * fp,const char * name,int closeit)1457 PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1458 {
1459     return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1460 }
1461 
1462 #undef PyRun_AnyFileFlags
1463 PyAPI_FUNC(int)
PyRun_AnyFileFlags(FILE * fp,const char * name,PyCompilerFlags * flags)1464 PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1465 {
1466     return PyRun_AnyFileExFlags(fp, name, 0, flags);
1467 }
1468 
1469 #undef PyRun_File
1470 PyAPI_FUNC(PyObject *)
PyRun_File(FILE * fp,const char * p,int s,PyObject * g,PyObject * l)1471 PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1472 {
1473     return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1474 }
1475 
1476 #undef PyRun_FileEx
1477 PyAPI_FUNC(PyObject *)
PyRun_FileEx(FILE * fp,const char * p,int s,PyObject * g,PyObject * l,int c)1478 PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1479 {
1480     return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1481 }
1482 
1483 #undef PyRun_FileFlags
1484 PyAPI_FUNC(PyObject *)
PyRun_FileFlags(FILE * fp,const char * p,int s,PyObject * g,PyObject * l,PyCompilerFlags * flags)1485 PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1486                 PyCompilerFlags *flags)
1487 {
1488     return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1489 }
1490 
1491 #undef PyRun_SimpleFile
1492 PyAPI_FUNC(int)
PyRun_SimpleFile(FILE * f,const char * p)1493 PyRun_SimpleFile(FILE *f, const char *p)
1494 {
1495     return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1496 }
1497 
1498 #undef PyRun_SimpleFileEx
1499 PyAPI_FUNC(int)
PyRun_SimpleFileEx(FILE * f,const char * p,int c)1500 PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1501 {
1502     return PyRun_SimpleFileExFlags(f, p, c, NULL);
1503 }
1504 
1505 
1506 #undef PyRun_String
1507 PyAPI_FUNC(PyObject *)
PyRun_String(const char * str,int s,PyObject * g,PyObject * l)1508 PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1509 {
1510     return PyRun_StringFlags(str, s, g, l, NULL);
1511 }
1512 
1513 #undef PyRun_SimpleString
1514 PyAPI_FUNC(int)
PyRun_SimpleString(const char * s)1515 PyRun_SimpleString(const char *s)
1516 {
1517     return PyRun_SimpleStringFlags(s, NULL);
1518 }
1519 
1520 #undef Py_CompileString
1521 PyAPI_FUNC(PyObject *)
Py_CompileString(const char * str,const char * p,int s)1522 Py_CompileString(const char *str, const char *p, int s)
1523 {
1524     return Py_CompileStringExFlags(str, p, s, NULL, -1);
1525 }
1526 
1527 #undef Py_CompileStringFlags
1528 PyAPI_FUNC(PyObject *)
Py_CompileStringFlags(const char * str,const char * p,int s,PyCompilerFlags * flags)1529 Py_CompileStringFlags(const char *str, const char *p, int s,
1530                       PyCompilerFlags *flags)
1531 {
1532     return Py_CompileStringExFlags(str, p, s, flags, -1);
1533 }
1534 
1535 #undef PyRun_InteractiveOne
1536 PyAPI_FUNC(int)
PyRun_InteractiveOne(FILE * f,const char * p)1537 PyRun_InteractiveOne(FILE *f, const char *p)
1538 {
1539     return PyRun_InteractiveOneFlags(f, p, NULL);
1540 }
1541 
1542 #undef PyRun_InteractiveLoop
1543 PyAPI_FUNC(int)
PyRun_InteractiveLoop(FILE * f,const char * p)1544 PyRun_InteractiveLoop(FILE *f, const char *p)
1545 {
1546     return PyRun_InteractiveLoopFlags(f, p, NULL);
1547 }
1548 
1549 #ifdef __cplusplus
1550 }
1551 #endif
1552