Bug Summary

File:Python/pythonrun.c
Location:line 1563, column 13
Description:Access to field 'ob_refcnt' results in a dereference of a null pointer (loaded from variable 'moduleName')

Annotated Source Code

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
19#ifdef HAVE_SIGNAL_H1
20#include <signal.h>
21#endif
22
23#ifdef MS_WINDOWS
24#include "malloc.h" /* for alloca */
25#endif
26
27#ifdef HAVE_LANGINFO_H1
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
32#ifdef MS_WINDOWS
33#undef BYTEchar
34#include "windows.h"
35#define PATH_MAX1024 MAXPATHLEN1024
36#endif
37
38#ifndef Py_REF_DEBUG
39#define PRINT_TOTAL_REFS()fprintf(__stderrp, "[%" "l" "d refs]\n", _Py_GetRefTotal())
40#else /* Py_REF_DEBUG */
41#define PRINT_TOTAL_REFS()fprintf(__stderrp, "[%" "l" "d refs]\n", _Py_GetRefTotal()) fprintf(stderr__stderrp, \
42 "[%" PY_FORMAT_SIZE_T"l" "d refs]\n", \
43 _Py_GetRefTotal())
44#endif
45
46#ifdef __cplusplus
47extern "C" {
48#endif
49
50extern wchar_t *Py_GetPath(void);
51
52extern grammar _PyParser_Grammar; /* From graminit.c */
53
54/* Forward */
55static void initmain(void);
56static void initfsencoding(void);
57static void initsite(void);
58static int initstdio(void);
59static void flush_io(void);
60static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
61 PyCompilerFlags *, PyArena *);
62static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
63 PyCompilerFlags *);
64static void err_input(perrdetail *);
65static void initsigs(void);
66static void call_py_exitfuncs(void);
67static void wait_for_thread_shutdown(void);
68static void call_ll_exitfuncs(void);
69extern void _PyUnicode_Init_PyUnicodeUCS2_Init(void);
70extern void _PyUnicode_Fini_PyUnicodeUCS2_Fini(void);
71extern int _PyLong_Init(void);
72extern void PyLong_Fini(void);
73
74#ifdef WITH_THREAD1
75extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
77#endif /* WITH_THREAD */
78
79int Py_DebugFlag; /* Needed by parser.c */
80int Py_VerboseFlag; /* Needed by import.c */
81int Py_QuietFlag; /* Needed by sysmodule.c */
82int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
83int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
84int Py_NoSiteFlag; /* Suppress 'import site' */
85int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
86int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
87int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
88int Py_FrozenFlag; /* Needed by getpath.c */
89int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
90int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
91int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
92
93/* PyModule_GetWarningsModule is no longer necessary as of 2.6
94since _warnings is builtin. This API should not be used. */
95PyObject *
96PyModule_GetWarningsModule(void)
97{
98 return PyImport_ImportModule("warnings");
99}
100
101static int initialized = 0;
102
103/* API to access the initialized flag -- useful for esoteric use */
104
105int
106Py_IsInitialized(void)
107{
108 return initialized;
109}
110
111/* Global initializations. Can be undone by Py_Finalize(). Don't
112 call this twice without an intervening Py_Finalize() call. When
113 initializations fail, a fatal error is issued and the function does
114 not return. On return, the first thread and interpreter state have
115 been created.
116
117 Locking: you must hold the interpreter lock while calling this.
118 (If the lock has not yet been initialized, that's equivalent to
119 having the lock, but you cannot use multiple threads.)
120
121*/
122
123static int
124add_flag(int flag, const char *envs)
125{
126 int env = atoi(envs);
127 if (flag < env)
128 flag = env;
129 if (flag < 1)
130 flag = 1;
131 return flag;
132}
133
134static char*
135get_codec_name(const char *encoding)
136{
137 char *name_utf8, *name_str;
138 PyObject *codec, *name = NULL((void *)0);
139
140 codec = _PyCodec_Lookup(encoding);
141 if (!codec)
142 goto error;
143
144 name = PyObject_GetAttrString(codec, "name");
145 Py_CLEAR(codec)do { if (codec) { PyObject *_py_tmp = (PyObject *)(codec); (codec
) = ((void *)0); do { if (_Py_RefTotal-- , --((PyObject*)(_py_tmp
))->ob_refcnt != 0) { if (((PyObject*)_py_tmp)->ob_refcnt
< 0) _Py_NegativeRefcount("Python/pythonrun.c", 145, (PyObject
*)(_py_tmp)); } else _Py_Dealloc((PyObject *)(_py_tmp)); } while
(0); } } while (0)
;
146 if (!name)
147 goto error;
148
149 name_utf8 = _PyUnicode_AsString(name);
150 if (name == NULL((void *)0))
151 goto error;
152 name_str = strdup(name_utf8);
153 Py_DECREF(name)do { if (_Py_RefTotal-- , --((PyObject*)(name))->ob_refcnt
!= 0) { if (((PyObject*)name)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 153, (PyObject *)(name)); } else _Py_Dealloc
((PyObject *)(name)); } while (0)
;
154 if (name_str == NULL((void *)0)) {
155 PyErr_NoMemory();
156 return NULL((void *)0);
157 }
158 return name_str;
159
160error:
161 Py_XDECREF(codec)do { if ((codec) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(codec))->ob_refcnt != 0) { if (((PyObject
*)codec)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 161, (PyObject *)(codec)); } else _Py_Dealloc((PyObject *)(
codec)); } while (0); } while (0)
;
162 Py_XDECREF(name)do { if ((name) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(name))->ob_refcnt != 0) { if (((PyObject
*)name)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 162, (PyObject *)(name)); } else _Py_Dealloc((PyObject *)(name
)); } while (0); } while (0)
;
163 return NULL((void *)0);
164}
165
166#if defined(HAVE_LANGINFO_H1) && defined(CODESET0)
167static char*
168get_codeset(void)
169{
170 char* codeset = nl_langinfo(CODESET0);
171 if (!codeset || codeset[0] == '\0') {
172 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
173 return NULL((void *)0);
174 }
175 return get_codec_name(codeset);
176}
177#endif
178
179void
180Py_InitializeEx(int install_sigs)
181{
182 PyInterpreterState *interp;
183 PyThreadState *tstate;
184 PyObject *bimod, *sysmod, *pstderr;
185 char *p;
186 extern void _Py_ReadyTypes(void);
187
188 if (initialized)
189 return;
190 initialized = 1;
191
192#if defined(HAVE_LANGINFO_H1) && defined(HAVE_SETLOCALE1)
193 /* Set up the LC_CTYPE locale, so we can obtain
194 the locale's charset without having to switch
195 locales. */
196 setlocale(LC_CTYPE2, "");
197#endif
198
199 if ((p = Py_GETENV("PYTHONDEBUG")(Py_IgnoreEnvironmentFlag ? ((void *)0) : getenv("PYTHONDEBUG"
))
) && *p != '\0')
200 Py_DebugFlag = add_flag(Py_DebugFlag, p);
201 if ((p = Py_GETENV("PYTHONVERBOSE")(Py_IgnoreEnvironmentFlag ? ((void *)0) : getenv("PYTHONVERBOSE"
))
) && *p != '\0')
202 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
203 if ((p = Py_GETENV("PYTHONOPTIMIZE")(Py_IgnoreEnvironmentFlag ? ((void *)0) : getenv("PYTHONOPTIMIZE"
))
) && *p != '\0')
204 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
205 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")(Py_IgnoreEnvironmentFlag ? ((void *)0) : getenv("PYTHONDONTWRITEBYTECODE"
))
) && *p != '\0')
206 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
207
208 interp = PyInterpreterState_New();
209 if (interp == NULL((void *)0))
210 Py_FatalError("Py_Initialize: can't make first interpreter");
211
212 tstate = PyThreadState_New(interp);
213 if (tstate == NULL((void *)0))
214 Py_FatalError("Py_Initialize: can't make first thread");
215 (void) PyThreadState_Swap(tstate);
216
217#ifdef WITH_THREAD1
218 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
219 destroying the GIL might fail when it is being referenced from
220 another running thread (see issue #9901).
221 Instead we destroy the previously created GIL here, which ensures
222 that we can call Py_Initialize / Py_Finalize multiple times. */
223 _PyEval_FiniThreads();
224
225 /* Auto-thread-state API */
226 _PyGILState_Init(interp, tstate);
227#endif /* WITH_THREAD */
228
229 _Py_ReadyTypes();
230
231 if (!_PyFrame_Init())
232 Py_FatalError("Py_Initialize: can't init frames");
233
234 if (!_PyLong_Init())
235 Py_FatalError("Py_Initialize: can't init longs");
236
237 if (!PyByteArray_Init())
238 Py_FatalError("Py_Initialize: can't init bytearray");
239
240 _PyFloat_Init();
241
242 interp->modules = PyDict_New();
243 if (interp->modules == NULL((void *)0))
244 Py_FatalError("Py_Initialize: can't make modules dictionary");
245 interp->modules_reloading = PyDict_New();
246 if (interp->modules_reloading == NULL((void *)0))
247 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
248
249 /* Init Unicode implementation; relies on the codec registry */
250 _PyUnicode_Init_PyUnicodeUCS2_Init();
251
252 bimod = _PyBuiltin_Init();
253 if (bimod == NULL((void *)0))
254 Py_FatalError("Py_Initialize: can't initialize builtins modules");
255 _PyImport_FixupBuiltin(bimod, "builtins");
256 interp->builtins = PyModule_GetDict(bimod);
257 if (interp->builtins == NULL((void *)0))
258 Py_FatalError("Py_Initialize: can't initialize builtins dict");
259 Py_INCREF(interp->builtins)( _Py_RefTotal++ , ((PyObject*)(interp->builtins))->ob_refcnt
++)
;
260
261 /* initialize builtin exceptions */
262 _PyExc_Init();
263
264 sysmod = _PySys_Init();
265 if (sysmod == NULL((void *)0))
266 Py_FatalError("Py_Initialize: can't initialize sys");
267 interp->sysdict = PyModule_GetDict(sysmod);
268 if (interp->sysdict == NULL((void *)0))
269 Py_FatalError("Py_Initialize: can't initialize sys dict");
270 Py_INCREF(interp->sysdict)( _Py_RefTotal++ , ((PyObject*)(interp->sysdict))->ob_refcnt
++)
;
271 _PyImport_FixupBuiltin(sysmod, "sys");
272 PySys_SetPath(Py_GetPath());
273 PyDict_SetItemString(interp->sysdict, "modules",
274 interp->modules);
275
276 /* Set up a preliminary stderr printer until we have enough
277 infrastructure for the io module in place. */
278 pstderr = PyFile_NewStdPrinter(fileno(stderr__stderrp));
279 if (pstderr == NULL((void *)0))
280 Py_FatalError("Py_Initialize: can't set preliminary stderr");
281 PySys_SetObject("stderr", pstderr);
282 PySys_SetObject("__stderr__", pstderr);
283 Py_DECREF(pstderr)do { if (_Py_RefTotal-- , --((PyObject*)(pstderr))->ob_refcnt
!= 0) { if (((PyObject*)pstderr)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 283, (PyObject *)(pstderr)); } else _Py_Dealloc
((PyObject *)(pstderr)); } while (0)
;
284
285 _PyImport_Init();
286
287 _PyImportHooks_Init();
288
289 /* Initialize _warnings. */
290 _PyWarnings_Init();
291
292 _PyTime_Init();
293
294 initfsencoding();
295
296 if (install_sigs)
297 initsigs(); /* Signal handling stuff, including initintr() */
298
299 initmain(); /* Module __main__ */
300 if (initstdio() < 0)
301 Py_FatalError(
302 "Py_Initialize: can't initialize sys standard streams");
303
304 /* Initialize warnings. */
305 if (PySys_HasWarnOptions()) {
306 PyObject *warnings_module = PyImport_ImportModule("warnings");
307 if (warnings_module == NULL((void *)0)) {
308 fprintf(stderr__stderrp, "'import warnings' failed; traceback:\n");
309 PyErr_Print();
310 }
311 Py_XDECREF(warnings_module)do { if ((warnings_module) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(warnings_module))->ob_refcnt != 0) { if
(((PyObject*)warnings_module)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 311, (PyObject *)(warnings_module)); }
else _Py_Dealloc((PyObject *)(warnings_module)); } while (0)
; } while (0)
;
312 }
313
314 if (!Py_NoSiteFlag)
315 initsite(); /* Module site */
316}
317
318void
319Py_Initialize(void)
320{
321 Py_InitializeEx(1);
322}
323
324
325#ifdef COUNT_ALLOCS
326extern void dump_counts(FILE*);
327#endif
328
329/* Flush stdout and stderr */
330
331static void
332flush_std_files(void)
333{
334 PyObject *fout = PySys_GetObject("stdout");
335 PyObject *ferr = PySys_GetObject("stderr");
336 PyObject *tmp;
337
338 if (fout != NULL((void *)0) && fout != Py_None(&_Py_NoneStruct)) {
339 tmp = PyObject_CallMethod(fout, "flush", "");
340 if (tmp == NULL((void *)0))
341 PyErr_WriteUnraisable(fout);
342 else
343 Py_DECREF(tmp)do { if (_Py_RefTotal-- , --((PyObject*)(tmp))->ob_refcnt !=
0) { if (((PyObject*)tmp)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 343, (PyObject *)(tmp)); } else _Py_Dealloc
((PyObject *)(tmp)); } while (0)
;
344 }
345
346 if (ferr != NULL((void *)0) && ferr != Py_None(&_Py_NoneStruct)) {
347 tmp = PyObject_CallMethod(ferr, "flush", "");
348 if (tmp == NULL((void *)0))
349 PyErr_Clear();
350 else
351 Py_DECREF(tmp)do { if (_Py_RefTotal-- , --((PyObject*)(tmp))->ob_refcnt !=
0) { if (((PyObject*)tmp)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 351, (PyObject *)(tmp)); } else _Py_Dealloc
((PyObject *)(tmp)); } while (0)
;
352 }
353}
354
355/* Undo the effect of Py_Initialize().
356
357 Beware: if multiple interpreter and/or thread states exist, these
358 are not wiped out; only the current thread and interpreter state
359 are deleted. But since everything else is deleted, those other
360 interpreter and thread states should no longer be used.
361
362 (XXX We should do better, e.g. wipe out all interpreters and
363 threads.)
364
365 Locking: as above.
366
367*/
368
369void
370Py_Finalize(void)
371{
372 PyInterpreterState *interp;
373 PyThreadState *tstate;
374
375 if (!initialized)
376 return;
377
378 wait_for_thread_shutdown();
379
380 /* The interpreter is still entirely intact at this point, and the
381 * exit funcs may be relying on that. In particular, if some thread
382 * or exit func is still waiting to do an import, the import machinery
383 * expects Py_IsInitialized() to return true. So don't say the
384 * interpreter is uninitialized until after the exit funcs have run.
385 * Note that Threading.py uses an exit func to do a join on all the
386 * threads created thru it, so this also protects pending imports in
387 * the threads created via Threading.
388 */
389 call_py_exitfuncs();
390 initialized = 0;
391
392 /* Flush stdout+stderr */
393 flush_std_files();
394
395 /* Get current thread state and interpreter pointer */
396 tstate = PyThreadState_GET()PyThreadState_Get();
397 interp = tstate->interp;
398
399 /* Disable signal handling */
400 PyOS_FiniInterrupts();
401
402 /* Clear type lookup cache */
403 PyType_ClearCache();
404
405 /* Collect garbage. This may call finalizers; it's nice to call these
406 * before all modules are destroyed.
407 * XXX If a __del__ or weakref callback is triggered here, and tries to
408 * XXX import a module, bad things can happen, because Python no
409 * XXX longer believes it's initialized.
410 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
411 * XXX is easy to provoke that way. I've also seen, e.g.,
412 * XXX Exception exceptions.ImportError: 'No module named sha'
413 * XXX in <function callback at 0x008F5718> ignored
414 * XXX but I'm unclear on exactly how that one happens. In any case,
415 * XXX I haven't seen a real-life report of either of these.
416 */
417 PyGC_Collect();
418#ifdef COUNT_ALLOCS
419 /* With COUNT_ALLOCS, it helps to run GC multiple times:
420 each collection might release some types from the type
421 list, so they become garbage. */
422 while (PyGC_Collect() > 0)
423 /* nothing */;
424#endif
425 /* We run this while most interpreter state is still alive, so that
426 debug information can be printed out */
427 _PyGC_Fini();
428
429 /* Destroy all modules */
430 PyImport_Cleanup();
431
432 /* Flush stdout+stderr (again, in case more was printed) */
433 flush_std_files();
434
435 /* Collect final garbage. This disposes of cycles created by
436 * new-style class definitions, for example.
437 * XXX This is disabled because it caused too many problems. If
438 * XXX a __del__ or weakref callback triggers here, Python code has
439 * XXX a hard time running, because even the sys module has been
440 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
441 * XXX One symptom is a sequence of information-free messages
442 * XXX coming from threads (if a __del__ or callback is invoked,
443 * XXX other threads can execute too, and any exception they encounter
444 * XXX triggers a comedy of errors as subsystem after subsystem
445 * XXX fails to find what it *expects* to find in sys to help report
446 * XXX the exception and consequent unexpected failures). I've also
447 * XXX seen segfaults then, after adding print statements to the
448 * XXX Python code getting called.
449 */
450#if 0
451 PyGC_Collect();
452#endif
453
454 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
455 _PyImport_Fini();
456
457 /* Debugging stuff */
458#ifdef COUNT_ALLOCS
459 dump_counts(stdout__stdoutp);
460#endif
461
462 PRINT_TOTAL_REFS()fprintf(__stderrp, "[%" "l" "d refs]\n", _Py_GetRefTotal());
463
464#ifdef Py_TRACE_REFS
465 /* Display all objects still alive -- this can invoke arbitrary
466 * __repr__ overrides, so requires a mostly-intact interpreter.
467 * Alas, a lot of stuff may still be alive now that will be cleaned
468 * up later.
469 */
470 if (Py_GETENV("PYTHONDUMPREFS")(Py_IgnoreEnvironmentFlag ? ((void *)0) : getenv("PYTHONDUMPREFS"
))
)
471 _Py_PrintReferences(stderr__stderrp);
472#endif /* Py_TRACE_REFS */
473
474 /* Clear interpreter state */
475 PyInterpreterState_Clear(interp);
476
477 /* Now we decref the exception classes. After this point nothing
478 can raise an exception. That's okay, because each Fini() method
479 below has been checked to make sure no exceptions are ever
480 raised.
481 */
482
483 _PyExc_Fini();
484
485 /* Cleanup auto-thread-state */
486#ifdef WITH_THREAD1
487 _PyGILState_Fini();
488#endif /* WITH_THREAD */
489
490 /* Delete current thread */
491 PyThreadState_Swap(NULL((void *)0));
492 PyInterpreterState_Delete(interp);
493
494 /* Sundry finalizers */
495 PyMethod_Fini();
496 PyFrame_Fini();
497 PyCFunction_Fini();
498 PyTuple_Fini();
499 PyList_Fini();
500 PySet_Fini();
501 PyBytes_Fini();
502 PyByteArray_Fini();
503 PyLong_Fini();
504 PyFloat_Fini();
505 PyDict_Fini();
506
507 /* Cleanup Unicode implementation */
508 _PyUnicode_Fini_PyUnicodeUCS2_Fini();
509
510 /* reset file system default encoding */
511 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
512 free((char*)Py_FileSystemDefaultEncoding);
513 Py_FileSystemDefaultEncoding = NULL((void *)0);
514 }
515
516 /* XXX Still allocated:
517 - various static ad-hoc pointers to interned strings
518 - int and float free list blocks
519 - whatever various modules and libraries allocate
520 */
521
522 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
523
524#ifdef Py_TRACE_REFS
525 /* Display addresses (& refcnts) of all objects still alive.
526 * An address can be used to find the repr of the object, printed
527 * above by _Py_PrintReferences.
528 */
529 if (Py_GETENV("PYTHONDUMPREFS")(Py_IgnoreEnvironmentFlag ? ((void *)0) : getenv("PYTHONDUMPREFS"
))
)
530 _Py_PrintReferenceAddresses(stderr__stderrp);
531#endif /* Py_TRACE_REFS */
532#ifdef PYMALLOC_DEBUG
533 if (Py_GETENV("PYTHONMALLOCSTATS")(Py_IgnoreEnvironmentFlag ? ((void *)0) : getenv("PYTHONMALLOCSTATS"
))
)
534 _PyObject_DebugMallocStats();
535#endif
536
537 call_ll_exitfuncs();
538}
539
540/* Create and initialize a new interpreter and thread, and return the
541 new thread. This requires that Py_Initialize() has been called
542 first.
543
544 Unsuccessful initialization yields a NULL pointer. Note that *no*
545 exception information is available even in this case -- the
546 exception information is held in the thread, and there is no
547 thread.
548
549 Locking: as above.
550
551*/
552
553PyThreadState *
554Py_NewInterpreter(void)
555{
556 PyInterpreterState *interp;
557 PyThreadState *tstate, *save_tstate;
558 PyObject *bimod, *sysmod;
559
560 if (!initialized)
561 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
562
563 interp = PyInterpreterState_New();
564 if (interp == NULL((void *)0))
565 return NULL((void *)0);
566
567 tstate = PyThreadState_New(interp);
568 if (tstate == NULL((void *)0)) {
569 PyInterpreterState_Delete(interp);
570 return NULL((void *)0);
571 }
572
573 save_tstate = PyThreadState_Swap(tstate);
574
575 /* XXX The following is lax in error checking */
576
577 interp->modules = PyDict_New();
578 interp->modules_reloading = PyDict_New();
579
580 bimod = _PyImport_FindBuiltin("builtins");
581 if (bimod != NULL((void *)0)) {
582 interp->builtins = PyModule_GetDict(bimod);
583 if (interp->builtins == NULL((void *)0))
584 goto handle_error;
585 Py_INCREF(interp->builtins)( _Py_RefTotal++ , ((PyObject*)(interp->builtins))->ob_refcnt
++)
;
586 }
587
588 /* initialize builtin exceptions */
589 _PyExc_Init();
590
591 sysmod = _PyImport_FindBuiltin("sys");
592 if (bimod != NULL((void *)0) && sysmod != NULL((void *)0)) {
593 PyObject *pstderr;
594 interp->sysdict = PyModule_GetDict(sysmod);
595 if (interp->sysdict == NULL((void *)0))
596 goto handle_error;
597 Py_INCREF(interp->sysdict)( _Py_RefTotal++ , ((PyObject*)(interp->sysdict))->ob_refcnt
++)
;
598 PySys_SetPath(Py_GetPath());
599 PyDict_SetItemString(interp->sysdict, "modules",
600 interp->modules);
601 /* Set up a preliminary stderr printer until we have enough
602 infrastructure for the io module in place. */
603 pstderr = PyFile_NewStdPrinter(fileno(stderr__stderrp));
604 if (pstderr == NULL((void *)0))
605 Py_FatalError("Py_Initialize: can't set preliminary stderr");
606 PySys_SetObject("stderr", pstderr);
607 PySys_SetObject("__stderr__", pstderr);
608 Py_DECREF(pstderr)do { if (_Py_RefTotal-- , --((PyObject*)(pstderr))->ob_refcnt
!= 0) { if (((PyObject*)pstderr)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 608, (PyObject *)(pstderr)); } else _Py_Dealloc
((PyObject *)(pstderr)); } while (0)
;
609
610 _PyImportHooks_Init();
611 if (initstdio() < 0)
612 Py_FatalError(
613 "Py_Initialize: can't initialize sys standard streams");
614 initmain();
615 if (!Py_NoSiteFlag)
616 initsite();
617 }
618
619 if (!PyErr_Occurred())
620 return tstate;
621
622handle_error:
623 /* Oops, it didn't work. Undo it all. */
624
625 PyErr_Print();
626 PyThreadState_Clear(tstate);
627 PyThreadState_Swap(save_tstate);
628 PyThreadState_Delete(tstate);
629 PyInterpreterState_Delete(interp);
630
631 return NULL((void *)0);
632}
633
634/* Delete an interpreter and its last thread. This requires that the
635 given thread state is current, that the thread has no remaining
636 frames, and that it is its interpreter's only remaining thread.
637 It is a fatal error to violate these constraints.
638
639 (Py_Finalize() doesn't have these constraints -- it zaps
640 everything, regardless.)
641
642 Locking: as above.
643
644*/
645
646void
647Py_EndInterpreter(PyThreadState *tstate)
648{
649 PyInterpreterState *interp = tstate->interp;
650
651 if (tstate != PyThreadState_GET()PyThreadState_Get())
652 Py_FatalError("Py_EndInterpreter: thread is not current");
653 if (tstate->frame != NULL((void *)0))
654 Py_FatalError("Py_EndInterpreter: thread still has a frame");
655 if (tstate != interp->tstate_head || tstate->next != NULL((void *)0))
656 Py_FatalError("Py_EndInterpreter: not the last thread");
657
658 PyImport_Cleanup();
659 PyInterpreterState_Clear(interp);
660 PyThreadState_Swap(NULL((void *)0));
661 PyInterpreterState_Delete(interp);
662}
663
664static wchar_t *progname = L"python";
665
666void
667Py_SetProgramName(wchar_t *pn)
668{
669 if (pn && *pn)
670 progname = pn;
671}
672
673wchar_t *
674Py_GetProgramName(void)
675{
676 return progname;
677}
678
679static wchar_t *default_home = NULL((void *)0);
680static wchar_t env_home[PATH_MAX1024+1];
681
682void
683Py_SetPythonHome(wchar_t *home)
684{
685 default_home = home;
686}
687
688wchar_t *
689Py_GetPythonHome(void)
690{
691 wchar_t *home = default_home;
692 if (home == NULL((void *)0) && !Py_IgnoreEnvironmentFlag) {
693 char* chome = Py_GETENV("PYTHONHOME")(Py_IgnoreEnvironmentFlag ? ((void *)0) : getenv("PYTHONHOME"
))
;
694 if (chome) {
695 size_t r = mbstowcs(env_home, chome, PATH_MAX1024+1);
696 if (r != (size_t)-1 && r <= PATH_MAX1024)
697 home = env_home;
698 }
699
700 }
701 return home;
702}
703
704/* Create __main__ module */
705
706static void
707initmain(void)
708{
709 PyObject *m, *d;
710 m = PyImport_AddModule("__main__");
711 if (m == NULL((void *)0))
712 Py_FatalError("can't create __main__ module");
713 d = PyModule_GetDict(m);
714 if (PyDict_GetItemString(d, "__builtins__") == NULL((void *)0)) {
715 PyObject *bimod = PyImport_ImportModule("builtins");
716 if (bimod == NULL((void *)0) ||
717 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
718 Py_FatalError("can't add __builtins__ to __main__");
719 Py_DECREF(bimod)do { if (_Py_RefTotal-- , --((PyObject*)(bimod))->ob_refcnt
!= 0) { if (((PyObject*)bimod)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 719, (PyObject *)(bimod)); } else _Py_Dealloc
((PyObject *)(bimod)); } while (0)
;
720 }
721}
722
723static void
724initfsencoding(void)
725{
726 PyObject *codec;
727#if defined(HAVE_LANGINFO_H1) && defined(CODESET0)
728 char *codeset = NULL((void *)0);
729
730 if (Py_FileSystemDefaultEncoding == NULL((void *)0)) {
731 /* On Unix, set the file system encoding according to the
732 user's preference, if the CODESET names a well-known
733 Python codec, and Py_FileSystemDefaultEncoding isn't
734 initialized by other means. */
735 codeset = get_codeset();
736 if (codeset == NULL((void *)0))
737 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
738
739 Py_FileSystemDefaultEncoding = codeset;
740 Py_HasFileSystemDefaultEncoding = 0;
741 return;
742 }
743#endif
744
745 /* the encoding is mbcs, utf-8 or ascii */
746 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
747 if (!codec) {
748 /* Such error can only occurs in critical situations: no more
749 * memory, import a module of the standard library failed,
750 * etc. */
751 Py_FatalError("Py_Initialize: unable to load the file system codec");
752 } else {
753 Py_DECREF(codec)do { if (_Py_RefTotal-- , --((PyObject*)(codec))->ob_refcnt
!= 0) { if (((PyObject*)codec)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 753, (PyObject *)(codec)); } else _Py_Dealloc
((PyObject *)(codec)); } while (0)
;
754 }
755}
756
757/* Import the site module (not into __main__ though) */
758
759static void
760initsite(void)
761{
762 PyObject *m;
763 m = PyImport_ImportModule("site");
764 if (m == NULL((void *)0)) {
765 PyErr_Print();
766 Py_Finalize();
767 exit(1);
768 }
769 else {
770 Py_DECREF(m)do { if (_Py_RefTotal-- , --((PyObject*)(m))->ob_refcnt !=
0) { if (((PyObject*)m)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 770, (PyObject *)(m)); } else _Py_Dealloc
((PyObject *)(m)); } while (0)
;
771 }
772}
773
774static PyObject*
775create_stdio(PyObject* io,
776 int fd, int write_mode, char* name,
777 char* encoding, char* errors)
778{
779 PyObject *buf = NULL((void *)0), *stream = NULL((void *)0), *text = NULL((void *)0), *raw = NULL((void *)0), *res;
780 const char* mode;
781 PyObject *line_buffering;
782 int buffering, isatty;
783
784 /* stdin is always opened in buffered mode, first because it shouldn't
785 make a difference in common use cases, second because TextIOWrapper
786 depends on the presence of a read1() method which only exists on
787 buffered streams.
788 */
789 if (Py_UnbufferedStdioFlag && write_mode)
790 buffering = 0;
791 else
792 buffering = -1;
793 if (write_mode)
794 mode = "wb";
795 else
796 mode = "rb";
797 buf = PyObject_CallMethod(io, "open", "isiOOOi",
798 fd, mode, buffering,
799 Py_None(&_Py_NoneStruct), Py_None(&_Py_NoneStruct), Py_None(&_Py_NoneStruct), 0);
800 if (buf == NULL((void *)0))
801 goto error;
802
803 if (buffering) {
804 raw = PyObject_GetAttrString(buf, "raw");
805 if (raw == NULL((void *)0))
806 goto error;
807 }
808 else {
809 raw = buf;
810 Py_INCREF(raw)( _Py_RefTotal++ , ((PyObject*)(raw))->ob_refcnt++);
811 }
812
813 text = PyUnicode_FromStringPyUnicodeUCS2_FromString(name);
814 if (text == NULL((void *)0) || PyObject_SetAttrString(raw, "name", text) < 0)
815 goto error;
816 res = PyObject_CallMethod(raw, "isatty", "");
817 if (res == NULL((void *)0))
818 goto error;
819 isatty = PyObject_IsTrue(res);
820 Py_DECREF(res)do { if (_Py_RefTotal-- , --((PyObject*)(res))->ob_refcnt !=
0) { if (((PyObject*)res)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 820, (PyObject *)(res)); } else _Py_Dealloc
((PyObject *)(res)); } while (0)
;
821 if (isatty == -1)
822 goto error;
823 if (isatty || Py_UnbufferedStdioFlag)
824 line_buffering = Py_True((PyObject *) &_Py_TrueStruct);
825 else
826 line_buffering = Py_False((PyObject *) &_Py_FalseStruct);
827
828 Py_CLEAR(raw)do { if (raw) { PyObject *_py_tmp = (PyObject *)(raw); (raw) =
((void *)0); do { if (_Py_RefTotal-- , --((PyObject*)(_py_tmp
))->ob_refcnt != 0) { if (((PyObject*)_py_tmp)->ob_refcnt
< 0) _Py_NegativeRefcount("Python/pythonrun.c", 828, (PyObject
*)(_py_tmp)); } else _Py_Dealloc((PyObject *)(_py_tmp)); } while
(0); } } while (0)
;
829 Py_CLEAR(text)do { if (text) { PyObject *_py_tmp = (PyObject *)(text); (text
) = ((void *)0); do { if (_Py_RefTotal-- , --((PyObject*)(_py_tmp
))->ob_refcnt != 0) { if (((PyObject*)_py_tmp)->ob_refcnt
< 0) _Py_NegativeRefcount("Python/pythonrun.c", 829, (PyObject
*)(_py_tmp)); } else _Py_Dealloc((PyObject *)(_py_tmp)); } while
(0); } } while (0)
;
830
831 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
832 buf, encoding, errors,
833 "\n", line_buffering);
834 Py_CLEAR(buf)do { if (buf) { PyObject *_py_tmp = (PyObject *)(buf); (buf) =
((void *)0); do { if (_Py_RefTotal-- , --((PyObject*)(_py_tmp
))->ob_refcnt != 0) { if (((PyObject*)_py_tmp)->ob_refcnt
< 0) _Py_NegativeRefcount("Python/pythonrun.c", 834, (PyObject
*)(_py_tmp)); } else _Py_Dealloc((PyObject *)(_py_tmp)); } while
(0); } } while (0)
;
835 if (stream == NULL((void *)0))
836 goto error;
837
838 if (write_mode)
839 mode = "w";
840 else
841 mode = "r";
842 text = PyUnicode_FromStringPyUnicodeUCS2_FromString(mode);
843 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
844 goto error;
845 Py_CLEAR(text)do { if (text) { PyObject *_py_tmp = (PyObject *)(text); (text
) = ((void *)0); do { if (_Py_RefTotal-- , --((PyObject*)(_py_tmp
))->ob_refcnt != 0) { if (((PyObject*)_py_tmp)->ob_refcnt
< 0) _Py_NegativeRefcount("Python/pythonrun.c", 845, (PyObject
*)(_py_tmp)); } else _Py_Dealloc((PyObject *)(_py_tmp)); } while
(0); } } while (0)
;
846 return stream;
847
848error:
849 Py_XDECREF(buf)do { if ((buf) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(buf))->ob_refcnt != 0) { if (((PyObject*
)buf)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 849, (PyObject *)(buf)); } else _Py_Dealloc((PyObject *)(buf
)); } while (0); } while (0)
;
850 Py_XDECREF(stream)do { if ((stream) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(stream))->ob_refcnt != 0) { if (((PyObject
*)stream)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 850, (PyObject *)(stream)); } else _Py_Dealloc((PyObject *)
(stream)); } while (0); } while (0)
;
851 Py_XDECREF(text)do { if ((text) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(text))->ob_refcnt != 0) { if (((PyObject
*)text)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 851, (PyObject *)(text)); } else _Py_Dealloc((PyObject *)(text
)); } while (0); } while (0)
;
852 Py_XDECREF(raw)do { if ((raw) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(raw))->ob_refcnt != 0) { if (((PyObject*
)raw)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 852, (PyObject *)(raw)); } else _Py_Dealloc((PyObject *)(raw
)); } while (0); } while (0)
;
853 return NULL((void *)0);
854}
855
856/* Initialize sys.stdin, stdout, stderr and builtins.open */
857static int
858initstdio(void)
859{
860 PyObject *iomod = NULL((void *)0), *wrapper;
861 PyObject *bimod = NULL((void *)0);
862 PyObject *m;
863 PyObject *std = NULL((void *)0);
864 int status = 0, fd;
865 PyObject * encoding_attr;
866 char *encoding = NULL((void *)0), *errors;
867
868 /* Hack to avoid a nasty recursion issue when Python is invoked
869 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
870 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL((void *)0)) {
871 goto error;
872 }
873 Py_DECREF(m)do { if (_Py_RefTotal-- , --((PyObject*)(m))->ob_refcnt !=
0) { if (((PyObject*)m)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 873, (PyObject *)(m)); } else _Py_Dealloc
((PyObject *)(m)); } while (0)
;
874
875 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
876 goto error;
877 }
878 Py_DECREF(m)do { if (_Py_RefTotal-- , --((PyObject*)(m))->ob_refcnt !=
0) { if (((PyObject*)m)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 878, (PyObject *)(m)); } else _Py_Dealloc
((PyObject *)(m)); } while (0)
;
879
880 if (!(bimod = PyImport_ImportModule("builtins"))) {
881 goto error;
882 }
883
884 if (!(iomod = PyImport_ImportModule("io"))) {
885 goto error;
886 }
887 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
888 goto error;
889 }
890
891 /* Set builtins.open */
892 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
893 Py_DECREF(wrapper)do { if (_Py_RefTotal-- , --((PyObject*)(wrapper))->ob_refcnt
!= 0) { if (((PyObject*)wrapper)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 893, (PyObject *)(wrapper)); } else _Py_Dealloc
((PyObject *)(wrapper)); } while (0)
;
894 goto error;
895 }
896 Py_DECREF(wrapper)do { if (_Py_RefTotal-- , --((PyObject*)(wrapper))->ob_refcnt
!= 0) { if (((PyObject*)wrapper)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 896, (PyObject *)(wrapper)); } else _Py_Dealloc
((PyObject *)(wrapper)); } while (0)
;
897
898 encoding = Py_GETENV("PYTHONIOENCODING")(Py_IgnoreEnvironmentFlag ? ((void *)0) : getenv("PYTHONIOENCODING"
))
;
899 errors = NULL((void *)0);
900 if (encoding) {
901 encoding = strdup(encoding);
902 errors = strchr(encoding, ':');
903 if (errors) {
904 *errors = '\0';
905 errors++;
906 }
907 }
908
909 /* Set sys.stdin */
910 fd = fileno(stdin__stdinp);
911 /* Under some conditions stdin, stdout and stderr may not be connected
912 * and fileno() may point to an invalid file descriptor. For example
913 * GUI apps don't have valid standard streams by default.
914 */
915 if (fd < 0) {
916#ifdef MS_WINDOWS
917 std = Py_None(&_Py_NoneStruct);
918 Py_INCREF(std)( _Py_RefTotal++ , ((PyObject*)(std))->ob_refcnt++);
919#else
920 goto error;
921#endif
922 }
923 else {
924 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
925 if (std == NULL((void *)0))
926 goto error;
927 } /* if (fd < 0) */
928 PySys_SetObject("__stdin__", std);
929 PySys_SetObject("stdin", std);
930 Py_DECREF(std)do { if (_Py_RefTotal-- , --((PyObject*)(std))->ob_refcnt !=
0) { if (((PyObject*)std)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 930, (PyObject *)(std)); } else _Py_Dealloc
((PyObject *)(std)); } while (0)
;
931
932 /* Set sys.stdout */
933 fd = fileno(stdout__stdoutp);
934 if (fd < 0) {
935#ifdef MS_WINDOWS
936 std = Py_None(&_Py_NoneStruct);
937 Py_INCREF(std)( _Py_RefTotal++ , ((PyObject*)(std))->ob_refcnt++);
938#else
939 goto error;
940#endif
941 }
942 else {
943 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
944 if (std == NULL((void *)0))
945 goto error;
946 } /* if (fd < 0) */
947 PySys_SetObject("__stdout__", std);
948 PySys_SetObject("stdout", std);
949 Py_DECREF(std)do { if (_Py_RefTotal-- , --((PyObject*)(std))->ob_refcnt !=
0) { if (((PyObject*)std)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 949, (PyObject *)(std)); } else _Py_Dealloc
((PyObject *)(std)); } while (0)
;
950
951#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
952 /* Set sys.stderr, replaces the preliminary stderr */
953 fd = fileno(stderr__stderrp);
954 if (fd < 0) {
955#ifdef MS_WINDOWS
956 std = Py_None(&_Py_NoneStruct);
957 Py_INCREF(std)( _Py_RefTotal++ , ((PyObject*)(std))->ob_refcnt++);
958#else
959 goto error;
960#endif
961 }
962 else {
963 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
964 if (std == NULL((void *)0))
965 goto error;
966 } /* if (fd < 0) */
967
968 /* Same as hack above, pre-import stderr's codec to avoid recursion
969 when import.c tries to write to stderr in verbose mode. */
970 encoding_attr = PyObject_GetAttrString(std, "encoding");
971 if (encoding_attr != NULL((void *)0)) {
972 const char * encoding;
973 encoding = _PyUnicode_AsString(encoding_attr);
974 if (encoding != NULL((void *)0)) {
975 _PyCodec_Lookup(encoding);
976 }
977 Py_DECREF(encoding_attr)do { if (_Py_RefTotal-- , --((PyObject*)(encoding_attr))->
ob_refcnt != 0) { if (((PyObject*)encoding_attr)->ob_refcnt
< 0) _Py_NegativeRefcount("Python/pythonrun.c", 977, (PyObject
*)(encoding_attr)); } else _Py_Dealloc((PyObject *)(encoding_attr
)); } while (0)
;
978 }
979 PyErr_Clear(); /* Not a fatal error if codec isn't available */
980
981 PySys_SetObject("__stderr__", std);
982 PySys_SetObject("stderr", std);
983 Py_DECREF(std)do { if (_Py_RefTotal-- , --((PyObject*)(std))->ob_refcnt !=
0) { if (((PyObject*)std)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 983, (PyObject *)(std)); } else _Py_Dealloc
((PyObject *)(std)); } while (0)
;
984#endif
985
986 if (0) {
987 error:
988 status = -1;
989 }
990
991 if (encoding)
992 free(encoding);
993 Py_XDECREF(bimod)do { if ((bimod) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(bimod))->ob_refcnt != 0) { if (((PyObject
*)bimod)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 993, (PyObject *)(bimod)); } else _Py_Dealloc((PyObject *)(
bimod)); } while (0); } while (0)
;
994 Py_XDECREF(iomod)do { if ((iomod) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(iomod))->ob_refcnt != 0) { if (((PyObject
*)iomod)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 994, (PyObject *)(iomod)); } else _Py_Dealloc((PyObject *)(
iomod)); } while (0); } while (0)
;
995 return status;
996}
997
998/* Parse input from a file and execute it */
999
1000int
1001PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
1002 PyCompilerFlags *flags)
1003{
1004 if (filename == NULL((void *)0))
1005 filename = "???";
1006 if (Py_FdIsInteractive(fp, filename)) {
1007 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1008 if (closeit)
1009 fclose(fp);
1010 return err;
1011 }
1012 else
1013 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
1014}
1015
1016int
1017PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
1018{
1019 PyObject *v;
1020 int ret;
1021 PyCompilerFlags local_flags;
1022
1023 if (flags == NULL((void *)0)) {
1024 flags = &local_flags;
1025 local_flags.cf_flags = 0;
1026 }
1027 v = PySys_GetObject("ps1");
1028 if (v == NULL((void *)0)) {
1029 PySys_SetObject("ps1", v = PyUnicode_FromStringPyUnicodeUCS2_FromString(">>> "));
1030 Py_XDECREF(v)do { if ((v) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(v))->ob_refcnt != 0) { if (((PyObject*)v)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1030
, (PyObject *)(v)); } else _Py_Dealloc((PyObject *)(v)); } while
(0); } while (0)
;
1031 }
1032 v = PySys_GetObject("ps2");
1033 if (v == NULL((void *)0)) {
1034 PySys_SetObject("ps2", v = PyUnicode_FromStringPyUnicodeUCS2_FromString("... "));
1035 Py_XDECREF(v)do { if ((v) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(v))->ob_refcnt != 0) { if (((PyObject*)v)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1035
, (PyObject *)(v)); } else _Py_Dealloc((PyObject *)(v)); } while
(0); } while (0)
;
1036 }
1037 for (;;) {
1038 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1039 PRINT_TOTAL_REFS()fprintf(__stderrp, "[%" "l" "d refs]\n", _Py_GetRefTotal());
1040 if (ret == E_EOF11)
1041 return 0;
1042 /*
1043 if (ret == E_NOMEM)
1044 return -1;
1045 */
1046 }
1047}
1048
1049/* compute parser flags based on compiler flags */
1050static int PARSER_FLAGS(PyCompilerFlags *flags)
1051{
1052 int parser_flags = 0;
1053 if (!flags)
1054 return 0;
1055 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT0x0200)
1056 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT0x0002;
1057 if (flags->cf_flags & PyCF_IGNORE_COOKIE0x0800)
1058 parser_flags |= PyPARSE_IGNORE_COOKIE0x0010;
1059 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL0x40000)
1060 parser_flags |= PyPARSE_BARRY_AS_BDFL0x0020;
1061 return parser_flags;
1062}
1063
1064#if 0
1065/* Keep an example of flags with future keyword support. */
1066#define PARSER_FLAGS(flags) \
1067 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT0x0200) ? \
1068 PyPARSE_DONT_IMPLY_DEDENT0x0002 : 0) \
1069 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT0x8000 ? \
1070 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
1071#endif
1072
1073int
1074PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
1075{
1076 PyObject *m, *d, *v, *w, *oenc = NULL((void *)0);
1077 mod_ty mod;
1078 PyArena *arena;
1079 char *ps1 = "", *ps2 = "", *enc = NULL((void *)0);
1080 int errcode = 0;
1081
1082 if (fp == stdin__stdinp) {
1083 /* Fetch encoding from sys.stdin */
1084 v = PySys_GetObject("stdin");
1085 if (v == NULL((void *)0) || v == Py_None(&_Py_NoneStruct))
1086 return -1;
1087 oenc = PyObject_GetAttrString(v, "encoding");
1088 if (!oenc)
1089 return -1;
1090 enc = _PyUnicode_AsString(oenc);
1091 if (enc == NULL((void *)0))
1092 return -1;
1093 }
1094 v = PySys_GetObject("ps1");
1095 if (v != NULL((void *)0)) {
1096 v = PyObject_Str(v);
1097 if (v == NULL((void *)0))
1098 PyErr_Clear();
1099 else if (PyUnicode_Check(v)((((((PyObject*)(v))->ob_type))->tp_flags & ((1L<<
28))) != 0)
) {
1100 ps1 = _PyUnicode_AsString(v);
1101 if (ps1 == NULL((void *)0)) {
1102 PyErr_Clear();
1103 ps1 = "";
1104 }
1105 }
1106 }
1107 w = PySys_GetObject("ps2");
1108 if (w != NULL((void *)0)) {
1109 w = PyObject_Str(w);
1110 if (w == NULL((void *)0))
1111 PyErr_Clear();
1112 else if (PyUnicode_Check(w)((((((PyObject*)(w))->ob_type))->tp_flags & ((1L<<
28))) != 0)
) {
1113 ps2 = _PyUnicode_AsString(w);
1114 if (ps2 == NULL((void *)0)) {
1115 PyErr_Clear();
1116 ps2 = "";
1117 }
1118 }
1119 }
1120 arena = PyArena_New();
1121 if (arena == NULL((void *)0)) {
1122 Py_XDECREF(v)do { if ((v) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(v))->ob_refcnt != 0) { if (((PyObject*)v)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1122
, (PyObject *)(v)); } else _Py_Dealloc((PyObject *)(v)); } while
(0); } while (0)
;
1123 Py_XDECREF(w)do { if ((w) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(w))->ob_refcnt != 0) { if (((PyObject*)w)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1123
, (PyObject *)(w)); } else _Py_Dealloc((PyObject *)(w)); } while
(0); } while (0)
;
1124 Py_XDECREF(oenc)do { if ((oenc) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(oenc))->ob_refcnt != 0) { if (((PyObject
*)oenc)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1124, (PyObject *)(oenc)); } else _Py_Dealloc((PyObject *)(
oenc)); } while (0); } while (0)
;
1125 return -1;
1126 }
1127 mod = PyParser_ASTFromFile(fp, filename, enc,
1128 Py_single_input256, ps1, ps2,
1129 flags, &errcode, arena);
1130 Py_XDECREF(v)do { if ((v) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(v))->ob_refcnt != 0) { if (((PyObject*)v)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1130
, (PyObject *)(v)); } else _Py_Dealloc((PyObject *)(v)); } while
(0); } while (0)
;
1131 Py_XDECREF(w)do { if ((w) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(w))->ob_refcnt != 0) { if (((PyObject*)w)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1131
, (PyObject *)(w)); } else _Py_Dealloc((PyObject *)(w)); } while
(0); } while (0)
;
1132 Py_XDECREF(oenc)do { if ((oenc) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(oenc))->ob_refcnt != 0) { if (((PyObject
*)oenc)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1132, (PyObject *)(oenc)); } else _Py_Dealloc((PyObject *)(
oenc)); } while (0); } while (0)
;
1133 if (mod == NULL((void *)0)) {
1134 PyArena_Free(arena);
1135 if (errcode == E_EOF11) {
1136 PyErr_Clear();
1137 return E_EOF11;
1138 }
1139 PyErr_Print();
1140 return -1;
1141 }
1142 m = PyImport_AddModule("__main__");
1143 if (m == NULL((void *)0)) {
1144 PyArena_Free(arena);
1145 return -1;
1146 }
1147 d = PyModule_GetDict(m);
1148 v = run_mod(mod, filename, d, d, flags, arena);
1149 PyArena_Free(arena);
1150 flush_io();
1151 if (v == NULL((void *)0)) {
1152 PyErr_Print();
1153 return -1;
1154 }
1155 Py_DECREF(v)do { if (_Py_RefTotal-- , --((PyObject*)(v))->ob_refcnt !=
0) { if (((PyObject*)v)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1155, (PyObject *)(v)); } else _Py_Dealloc
((PyObject *)(v)); } while (0)
;
1156 return 0;
1157}
1158
1159/* Check whether a file maybe a pyc file: Look at the extension,
1160 the file type, and, if we may close it, at the first few bytes. */
1161
1162static int
1163maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
1164{
1165 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1166 return 1;
1167
1168 /* Only look into the file if we are allowed to close it, since
1169 it then should also be seekable. */
1170 if (closeit) {
1171 /* Read only two bytes of the magic. If the file was opened in
1172 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1173 be read as they are on disk. */
1174 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1175 unsigned char buf[2];
1176 /* Mess: In case of -x, the stream is NOT at its start now,
1177 and ungetc() was used to push back the first newline,
1178 which makes the current stream position formally undefined,
1179 and a x-platform nightmare.
1180 Unfortunately, we have no direct way to know whether -x
1181 was specified. So we use a terrible hack: if the current
1182 stream position is not 0, we assume -x was specified, and
1183 give up. Bug 132850 on SourceForge spells out the
1184 hopelessness of trying anything else (fseek and ftell
1185 don't work predictably x-platform for text-mode files).
1186 */
1187 int ispyc = 0;
1188 if (ftell(fp) == 0) {
1189 if (fread(buf, 1, 2, fp) == 2 &&
1190 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1191 ispyc = 1;
1192 rewind(fp);
1193 }
1194 return ispyc;
1195 }
1196 return 0;
1197}
1198
1199int
1200PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
1201 PyCompilerFlags *flags)
1202{
1203 PyObject *m, *d, *v;
1204 const char *ext;
1205 int set_file_name = 0, ret;
1206 size_t len;
1207
1208 m = PyImport_AddModule("__main__");
1209 if (m == NULL((void *)0))
1210 return -1;
1211 d = PyModule_GetDict(m);
1212 if (PyDict_GetItemString(d, "__file__") == NULL((void *)0)) {
1213 PyObject *f;
1214 f = PyUnicode_DecodeFSDefaultPyUnicodeUCS2_DecodeFSDefault(filename);
1215 if (f == NULL((void *)0))
1216 return -1;
1217 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1218 Py_DECREF(f)do { if (_Py_RefTotal-- , --((PyObject*)(f))->ob_refcnt !=
0) { if (((PyObject*)f)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1218, (PyObject *)(f)); } else _Py_Dealloc
((PyObject *)(f)); } while (0)
;
1219 return -1;
1220 }
1221 if (PyDict_SetItemString(d, "__cached__", Py_None(&_Py_NoneStruct)) < 0)
1222 return -1;
1223 set_file_name = 1;
1224 Py_DECREF(f)do { if (_Py_RefTotal-- , --((PyObject*)(f))->ob_refcnt !=
0) { if (((PyObject*)f)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1224, (PyObject *)(f)); } else _Py_Dealloc
((PyObject *)(f)); } while (0)
;
1225 }
1226 len = strlen(filename);
1227 ext = filename + len - (len > 4 ? 4 : 0);
1228 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1229 /* Try to run a pyc file. First, re-open in binary */
1230 if (closeit)
1231 fclose(fp);
1232 if ((fp = fopen(filename, "rb")) == NULL((void *)0)) {
1233 fprintf(stderr__stderrp, "python: Can't reopen .pyc file\n");
1234 ret = -1;
1235 goto done;
1236 }
1237 /* Turn on optimization if a .pyo file is given */
1238 if (strcmp(ext, ".pyo") == 0)
1239 Py_OptimizeFlag = 1;
1240 v = run_pyc_file(fp, filename, d, d, flags);
1241 } else {
1242 v = PyRun_FileExFlags(fp, filename, Py_file_input257, d, d,
1243 closeit, flags);
1244 }
1245 flush_io();
1246 if (v == NULL((void *)0)) {
1247 PyErr_Print();
1248 ret = -1;
1249 goto done;
1250 }
1251 Py_DECREF(v)do { if (_Py_RefTotal-- , --((PyObject*)(v))->ob_refcnt !=
0) { if (((PyObject*)v)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1251, (PyObject *)(v)); } else _Py_Dealloc
((PyObject *)(v)); } while (0)
;
1252 ret = 0;
1253 done:
1254 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1255 PyErr_Clear();
1256 return ret;
1257}
1258
1259int
1260PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
1261{
1262 PyObject *m, *d, *v;
1263 m = PyImport_AddModule("__main__");
1264 if (m == NULL((void *)0))
1265 return -1;
1266 d = PyModule_GetDict(m);
1267 v = PyRun_StringFlags(command, Py_file_input257, d, d, flags);
1268 if (v == NULL((void *)0)) {
1269 PyErr_Print();
1270 return -1;
1271 }
1272 Py_DECREF(v)do { if (_Py_RefTotal-- , --((PyObject*)(v))->ob_refcnt !=
0) { if (((PyObject*)v)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1272, (PyObject *)(v)); } else _Py_Dealloc
((PyObject *)(v)); } while (0)
;
1273 return 0;
1274}
1275
1276static int
1277parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1278 int *lineno, int *offset, const char **text)
1279{
1280 long hold;
1281 PyObject *v;
1282
1283 /* old style errors */
1284 if (PyTuple_Check(err)((((((PyObject*)(err))->ob_type))->tp_flags & ((1L<<
26))) != 0)
)
1285 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1286 lineno, offset, text);
1287
1288 /* new style errors. `err' is an instance */
1289
1290 if (! (v = PyObject_GetAttrString(err, "msg")))
1291 goto finally;
1292 *message = v;
1293
1294 if (!(v = PyObject_GetAttrString(err, "filename")))
1295 goto finally;
1296 if (v == Py_None(&_Py_NoneStruct))
1297 *filename = NULL((void *)0);
1298 else if (! (*filename = _PyUnicode_AsString(v)))
1299 goto finally;
1300
1301 Py_DECREF(v)do { if (_Py_RefTotal-- , --((PyObject*)(v))->ob_refcnt !=
0) { if (((PyObject*)v)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1301, (PyObject *)(v)); } else _Py_Dealloc
((PyObject *)(v)); } while (0)
;
1302 if (!(v = PyObject_GetAttrString(err, "lineno")))
1303 goto finally;
1304 hold = PyLong_AsLong(v);
1305 Py_DECREF(v)do { if (_Py_RefTotal-- , --((PyObject*)(v))->ob_refcnt !=
0) { if (((PyObject*)v)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1305, (PyObject *)(v)); } else _Py_Dealloc
((PyObject *)(v)); } while (0)
;
1306 v = NULL((void *)0);
1307 if (hold < 0 && PyErr_Occurred())
1308 goto finally;
1309 *lineno = (int)hold;
1310
1311 if (!(v = PyObject_GetAttrString(err, "offset")))
1312 goto finally;
1313 if (v == Py_None(&_Py_NoneStruct)) {
1314 *offset = -1;
1315 Py_DECREF(v)do { if (_Py_RefTotal-- , --((PyObject*)(v))->ob_refcnt !=
0) { if (((PyObject*)v)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1315, (PyObject *)(v)); } else _Py_Dealloc
((PyObject *)(v)); } while (0)
;
1316 v = NULL((void *)0);
1317 } else {
1318 hold = PyLong_AsLong(v);
1319 Py_DECREF(v)do { if (_Py_RefTotal-- , --((PyObject*)(v))->ob_refcnt !=
0) { if (((PyObject*)v)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1319, (PyObject *)(v)); } else _Py_Dealloc
((PyObject *)(v)); } while (0)
;
1320 v = NULL((void *)0);
1321 if (hold < 0 && PyErr_Occurred())
1322 goto finally;
1323 *offset = (int)hold;
1324 }
1325
1326 if (!(v = PyObject_GetAttrString(err, "text")))
1327 goto finally;
1328 if (v == Py_None(&_Py_NoneStruct))
1329 *text = NULL((void *)0);
1330 else if (!PyUnicode_Check(v)((((((PyObject*)(v))->ob_type))->tp_flags & ((1L<<
28))) != 0)
||
1331 !(*text = _PyUnicode_AsString(v)))
1332 goto finally;
1333 Py_DECREF(v)do { if (_Py_RefTotal-- , --((PyObject*)(v))->ob_refcnt !=
0) { if (((PyObject*)v)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1333, (PyObject *)(v)); } else _Py_Dealloc
((PyObject *)(v)); } while (0)
;
1334 return 1;
1335
1336finally:
1337 Py_XDECREF(v)do { if ((v) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(v))->ob_refcnt != 0) { if (((PyObject*)v)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1337
, (PyObject *)(v)); } else _Py_Dealloc((PyObject *)(v)); } while
(0); } while (0)
;
1338 return 0;
1339}
1340
1341void
1342PyErr_Print(void)
1343{
1344 PyErr_PrintEx(1);
1345}
1346
1347static void
1348print_error_text(PyObject *f, int offset, const char *text)
1349{
1350 char *nl;
1351 if (offset >= 0) {
1352 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1353 offset--;
1354 for (;;) {
1355 nl = strchr(text, '\n');
1356 if (nl == NULL((void *)0) || nl-text >= offset)
1357 break;
1358 offset -= (int)(nl+1-text);
1359 text = nl+1;
1360 }
1361 while (*text == ' ' || *text == '\t') {
1362 text++;
1363 offset--;
1364 }
1365 }
1366 PyFile_WriteString(" ", f);
1367 PyFile_WriteString(text, f);
1368 if (*text == '\0' || text[strlen(text)-1] != '\n')
1369 PyFile_WriteString("\n", f);
1370 if (offset == -1)
1371 return;
1372 PyFile_WriteString(" ", f);
1373 while (--offset > 0)
1374 PyFile_WriteString(" ", f);
1375 PyFile_WriteString("^\n", f);
1376}
1377
1378static void
1379handle_system_exit(void)
1380{
1381 PyObject *exception, *value, *tb;
1382 int exitcode = 0;
1383
1384 if (Py_InspectFlag)
1385 /* Don't exit if -i flag was given. This flag is set to 0
1386 * when entering interactive mode for inspecting. */
1387 return;
1388
1389 PyErr_Fetch(&exception, &value, &tb);
1390 fflush(stdout__stdoutp);
1391 if (value == NULL((void *)0) || value == Py_None(&_Py_NoneStruct))
1392 goto done;
1393 if (PyExceptionInstance_Check(value)((((value)->ob_type)->tp_flags & ((1L<<30))) !=
0)
) {
1394 /* The error code should be in the `code' attribute. */
1395 PyObject *code = PyObject_GetAttrString(value, "code");
1396 if (code) {
1397 Py_DECREF(value)do { if (_Py_RefTotal-- , --((PyObject*)(value))->ob_refcnt
!= 0) { if (((PyObject*)value)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1397, (PyObject *)(value)); } else _Py_Dealloc
((PyObject *)(value)); } while (0)
;
1398 value = code;
1399 if (value == Py_None(&_Py_NoneStruct))
1400 goto done;
1401 }
1402 /* If we failed to dig out the 'code' attribute,
1403 just let the else clause below print the error. */
1404 }
1405 if (PyLong_Check(value)((((((PyObject*)(value))->ob_type))->tp_flags & ((1L
<<24))) != 0)
)
1406 exitcode = (int)PyLong_AsLong(value);
1407 else {
1408 PyObject *sys_stderr = PySys_GetObject("stderr");
1409 if (sys_stderr != NULL((void *)0) && sys_stderr != Py_None(&_Py_NoneStruct)) {
1410 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW1);
1411 } else {
1412 PyObject_Print(value, stderr__stderrp, Py_PRINT_RAW1);
1413 fflush(stderr__stderrp);
1414 }
1415 PySys_WriteStderr("\n");
1416 exitcode = 1;
1417 }
1418 done:
1419 /* Restore and clear the exception info, in order to properly decref
1420 * the exception, value, and traceback. If we just exit instead,
1421 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1422 * some finalizers from running.
1423 */
1424 PyErr_Restore(exception, value, tb);
1425 PyErr_Clear();
1426 Py_Exit(exitcode);
1427 /* NOTREACHED */
1428}
1429
1430void
1431PyErr_PrintEx(int set_sys_last_vars)
1432{
1433 PyObject *exception, *v, *tb, *hook;
1434
1435 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1436 handle_system_exit();
1437 }
1438 PyErr_Fetch(&exception, &v, &tb);
1439 if (exception == NULL((void *)0))
1440 return;
1441 PyErr_NormalizeException(&exception, &v, &tb);
1442 if (tb == NULL((void *)0)) {
1443 tb = Py_None(&_Py_NoneStruct);
1444 Py_INCREF(tb)( _Py_RefTotal++ , ((PyObject*)(tb))->ob_refcnt++);
1445 }
1446 PyException_SetTraceback(v, tb);
1447 if (exception == NULL((void *)0))
1448 return;
1449 /* Now we know v != NULL too */
1450 if (set_sys_last_vars) {
1451 PySys_SetObject("last_type", exception);
1452 PySys_SetObject("last_value", v);
1453 PySys_SetObject("last_traceback", tb);
1454 }
1455 hook = PySys_GetObject("excepthook");
1456 if (hook) {
1457 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1458 PyObject *result = PyEval_CallObject(hook, args)PyEval_CallObjectWithKeywords(hook, args, (PyObject *)((void *
)0))
;
1459 if (result == NULL((void *)0)) {
1460 PyObject *exception2, *v2, *tb2;
1461 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1462 handle_system_exit();
1463 }
1464 PyErr_Fetch(&exception2, &v2, &tb2);
1465 PyErr_NormalizeException(&exception2, &v2, &tb2);
1466 /* It should not be possible for exception2 or v2
1467 to be NULL. However PyErr_Display() can't
1468 tolerate NULLs, so just be safe. */
1469 if (exception2 == NULL((void *)0)) {
1470 exception2 = Py_None(&_Py_NoneStruct);
1471 Py_INCREF(exception2)( _Py_RefTotal++ , ((PyObject*)(exception2))->ob_refcnt++);
1472 }
1473 if (v2 == NULL((void *)0)) {
1474 v2 = Py_None(&_Py_NoneStruct);
1475 Py_INCREF(v2)( _Py_RefTotal++ , ((PyObject*)(v2))->ob_refcnt++);
1476 }
1477 fflush(stdout__stdoutp);
1478 PySys_WriteStderr("Error in sys.excepthook:\n");
1479 PyErr_Display(exception2, v2, tb2);
1480 PySys_WriteStderr("\nOriginal exception was:\n");
1481 PyErr_Display(exception, v, tb);
1482 Py_DECREF(exception2)do { if (_Py_RefTotal-- , --((PyObject*)(exception2))->ob_refcnt
!= 0) { if (((PyObject*)exception2)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1482, (PyObject *)(exception2)); } else
_Py_Dealloc((PyObject *)(exception2)); } while (0)
;
1483 Py_DECREF(v2)do { if (_Py_RefTotal-- , --((PyObject*)(v2))->ob_refcnt !=
0) { if (((PyObject*)v2)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1483, (PyObject *)(v2)); } else _Py_Dealloc
((PyObject *)(v2)); } while (0)
;
1484 Py_XDECREF(tb2)do { if ((tb2) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(tb2))->ob_refcnt != 0) { if (((PyObject*
)tb2)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1484, (PyObject *)(tb2)); } else _Py_Dealloc((PyObject *)(tb2
)); } while (0); } while (0)
;
1485 }
1486 Py_XDECREF(result)do { if ((result) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(result))->ob_refcnt != 0) { if (((PyObject
*)result)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1486, (PyObject *)(result)); } else _Py_Dealloc((PyObject *
)(result)); } while (0); } while (0)
;
1487 Py_XDECREF(args)do { if ((args) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(args))->ob_refcnt != 0) { if (((PyObject
*)args)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1487, (PyObject *)(args)); } else _Py_Dealloc((PyObject *)(
args)); } while (0); } while (0)
;
1488 } else {
1489 PySys_WriteStderr("sys.excepthook is missing\n");
1490 PyErr_Display(exception, v, tb);
1491 }
1492 Py_XDECREF(exception)do { if ((exception) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(exception))->ob_refcnt != 0) { if (((PyObject
*)exception)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1492, (PyObject *)(exception)); } else _Py_Dealloc((PyObject
*)(exception)); } while (0); } while (0)
;
1493 Py_XDECREF(v)do { if ((v) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(v))->ob_refcnt != 0) { if (((PyObject*)v)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1493
, (PyObject *)(v)); } else _Py_Dealloc((PyObject *)(v)); } while
(0); } while (0)
;
1494 Py_XDECREF(tb)do { if ((tb) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(tb))->ob_refcnt != 0) { if (((PyObject*)tb
)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1494, (PyObject *)(tb)); } else _Py_Dealloc((PyObject *)(tb
)); } while (0); } while (0)
;
1495}
1496
1497static void
1498print_exception(PyObject *f, PyObject *value)
1499{
1500 int err = 0;
1501 PyObject *type, *tb;
1502
1503 if (!PyExceptionInstance_Check(value)((((value)->ob_type)->tp_flags & ((1L<<30))) !=
0)
) {
1
Taking false branch
1504 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1505 PyFile_WriteString(Py_TYPE(value)(((PyObject*)(value))->ob_type)->tp_name, f);
1506 PyFile_WriteString(" found\n", f);
1507 return;
1508 }
1509
1510 Py_INCREF(value)( _Py_RefTotal++ , ((PyObject*)(value))->ob_refcnt++);
1511 fflush(stdout__stdoutp);
1512 type = (PyObject *) Py_TYPE(value)(((PyObject*)(value))->ob_type);
1513 tb = PyException_GetTraceback(value);
1514 if (tb && tb != Py_None(&_Py_NoneStruct))
2
Taking false branch
1515 err = PyTraceBack_Print(tb, f);
1516 if (err == 0 &&
3
Taking false branch
1517 PyObject_HasAttrString(value, "print_file_and_line"))
1518 {
1519 PyObject *message;
1520 const char *filename, *text;
1521 int lineno, offset;
1522 if (!parse_syntax_error(value, &message, &filename,
1523 &lineno, &offset, &text))
1524 PyErr_Clear();
1525 else {
1526 char buf[10];
1527 PyFile_WriteString(" File \"", f);
1528 if (filename == NULL((void *)0))
1529 PyFile_WriteString("<string>", f);
1530 else
1531 PyFile_WriteString(filename, f);
1532 PyFile_WriteString("\", line ", f);
1533 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1534 PyFile_WriteString(buf, f);
1535 PyFile_WriteString("\n", f);
1536 if (text != NULL((void *)0))
1537 print_error_text(f, offset, text);
1538 Py_DECREF(value)do { if (_Py_RefTotal-- , --((PyObject*)(value))->ob_refcnt
!= 0) { if (((PyObject*)value)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1538, (PyObject *)(value)); } else _Py_Dealloc
((PyObject *)(value)); } while (0)
;
1539 value = message;
1540 /* Can't be bothered to check all those
1541 PyFile_WriteString() calls */
1542 if (PyErr_Occurred())
1543 err = -1;
1544 }
1545 }
1546 if (err) {
4
Taking false branch
1547 /* Don't do anything else */
1548 }
1549 else {
1550 PyObject* moduleName;
1551 char* className;
1552 assert(PyExceptionClass_Check(type))(__builtin_expect(!((((((((PyObject*)((type)))->ob_type))->
tp_flags & ((1L<<31))) != 0) && ((((PyTypeObject
*)(type))->tp_flags & ((1L<<30))) != 0))), 0) ? __assert_rtn
(__func__, "Python/pythonrun.c", 1552, "PyExceptionClass_Check(type)"
) : (void)0)
;
1553 className = PyExceptionClass_Name(type)((char *)(((PyTypeObject*)(type))->tp_name));
1554 if (className != NULL((void *)0)) {
5
Taking false branch
1555 char *dot = strrchr(className, '.');
1556 if (dot != NULL((void *)0))
1557 className = dot+1;
1558 }
1559
1560 moduleName = PyObject_GetAttrString(type, "__module__");
1561 if (moduleName == NULL((void *)0) || !PyUnicode_Check(moduleName)((((((PyObject*)(moduleName))->ob_type))->tp_flags &
((1L<<28))) != 0)
)
6
Taking true branch
1562 {
1563 Py_DECREF(moduleName)do { if (_Py_RefTotal-- , --((PyObject*)(moduleName))->ob_refcnt
!= 0) { if (((PyObject*)moduleName)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1563, (PyObject *)(moduleName)); } else
_Py_Dealloc((PyObject *)(moduleName)); } while (0)
;
7
Within the expansion of the macro 'Py_DECREF':
a
Access to field 'ob_refcnt' results in a dereference of a null pointer (loaded from variable 'moduleName')
1564 err = PyFile_WriteString("<unknown>", f);
1565 }
1566 else {
1567 char* modstr = _PyUnicode_AsString(moduleName);
1568 if (modstr && strcmp(modstr, "builtins"))
1569 {
1570 err = PyFile_WriteString(modstr, f);
1571 err += PyFile_WriteString(".", f);
1572 }
1573 Py_DECREF(moduleName)do { if (_Py_RefTotal-- , --((PyObject*)(moduleName))->ob_refcnt
!= 0) { if (((PyObject*)moduleName)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1573, (PyObject *)(moduleName)); } else
_Py_Dealloc((PyObject *)(moduleName)); } while (0)
;
1574 }
1575 if (err == 0) {
1576 if (className == NULL((void *)0))
1577 err = PyFile_WriteString("<unknown>", f);
1578 else
1579 err = PyFile_WriteString(className, f);
1580 }
1581 }
1582 if (err == 0 && (value != Py_None(&_Py_NoneStruct))) {
1583 PyObject *s = PyObject_Str(value);
1584 /* only print colon if the str() of the
1585 object is not the empty string
1586 */
1587 if (s == NULL((void *)0))
1588 err = -1;
1589 else if (!PyUnicode_Check(s)((((((PyObject*)(s))->ob_type))->tp_flags & ((1L<<
28))) != 0)
||
1590 PyUnicode_GetSizePyUnicodeUCS2_GetSize(s) != 0)
1591 err = PyFile_WriteString(": ", f);
1592 if (err == 0)
1593 err = PyFile_WriteObject(s, f, Py_PRINT_RAW1);
1594 Py_XDECREF(s)do { if ((s) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(s))->ob_refcnt != 0) { if (((PyObject*)s)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1594
, (PyObject *)(s)); } else _Py_Dealloc((PyObject *)(s)); } while
(0); } while (0)
;
1595 }
1596 /* try to write a newline in any case */
1597 err += PyFile_WriteString("\n", f);
1598 Py_XDECREF(tb)do { if ((tb) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(tb))->ob_refcnt != 0) { if (((PyObject*)tb
)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1598, (PyObject *)(tb)); } else _Py_Dealloc((PyObject *)(tb
)); } while (0); } while (0)
;
1599 Py_DECREF(value)do { if (_Py_RefTotal-- , --((PyObject*)(value))->ob_refcnt
!= 0) { if (((PyObject*)value)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1599, (PyObject *)(value)); } else _Py_Dealloc
((PyObject *)(value)); } while (0)
;
1600 /* If an error happened here, don't show it.
1601 XXX This is wrong, but too many callers rely on this behavior. */
1602 if (err != 0)
1603 PyErr_Clear();
1604}
1605
1606static const char *cause_message =
1607 "\nThe above exception was the direct cause "
1608 "of the following exception:\n\n";
1609
1610static const char *context_message =
1611 "\nDuring handling of the above exception, "
1612 "another exception occurred:\n\n";
1613
1614static void
1615print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1616{
1617 int err = 0, res;
1618 PyObject *cause, *context;
1619
1620 if (seen != NULL((void *)0)) {
1621 /* Exception chaining */
1622 if (PySet_Add(seen, value) == -1)
1623 PyErr_Clear();
1624 else if (PyExceptionInstance_Check(value)((((value)->ob_type)->tp_flags & ((1L<<30))) !=
0)
) {
1625 cause = PyException_GetCause(value);
1626 context = PyException_GetContext(value);
1627 if (cause) {
1628 res = PySet_Contains(seen, cause);
1629 if (res == -1)
1630 PyErr_Clear();
1631 if (res == 0) {
1632 print_exception_recursive(
1633 f, cause, seen);
1634 err |= PyFile_WriteString(
1635 cause_message, f);
1636 }
1637 }
1638 else if (context) {
1639 res = PySet_Contains(seen, context);
1640 if (res == -1)
1641 PyErr_Clear();
1642 if (res == 0) {
1643 print_exception_recursive(
1644 f, context, seen);
1645 err |= PyFile_WriteString(
1646 context_message, f);
1647 }
1648 }
1649 Py_XDECREF(context)do { if ((context) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(context))->ob_refcnt != 0) { if (((PyObject
*)context)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1649, (PyObject *)(context)); } else _Py_Dealloc((PyObject *
)(context)); } while (0); } while (0)
;
1650 Py_XDECREF(cause)do { if ((cause) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(cause))->ob_refcnt != 0) { if (((PyObject
*)cause)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1650, (PyObject *)(cause)); } else _Py_Dealloc((PyObject *)
(cause)); } while (0); } while (0)
;
1651 }
1652 }
1653 print_exception(f, value);
1654 if (err != 0)
1655 PyErr_Clear();
1656}
1657
1658void
1659PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1660{
1661 PyObject *seen;
1662 PyObject *f = PySys_GetObject("stderr");
1663 if (f == Py_None(&_Py_NoneStruct)) {
1664 /* pass */
1665 }
1666 else if (f == NULL((void *)0)) {
1667 _PyObject_Dump(value);
1668 fprintf(stderr__stderrp, "lost sys.stderr\n");
1669 }
1670 else {
1671 /* We choose to ignore seen being possibly NULL, and report
1672 at least the main exception (it could be a MemoryError).
1673 */
1674 seen = PySet_New(NULL((void *)0));
1675 if (seen == NULL((void *)0))
1676 PyErr_Clear();
1677 print_exception_recursive(f, value, seen);
1678 Py_XDECREF(seen)do { if ((seen) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(seen))->ob_refcnt != 0) { if (((PyObject
*)seen)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 1678, (PyObject *)(seen)); } else _Py_Dealloc((PyObject *)(
seen)); } while (0); } while (0)
;
1679 }
1680}
1681
1682PyObject *
1683PyRun_StringFlags(const char *str, int start, PyObject *globals,
1684 PyObject *locals, PyCompilerFlags *flags)
1685{
1686 PyObject *ret = NULL((void *)0);
1687 mod_ty mod;
1688 PyArena *arena = PyArena_New();
1689 if (arena == NULL((void *)0))
1690 return NULL((void *)0);
1691
1692 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1693 if (mod != NULL((void *)0))
1694 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1695 PyArena_Free(arena);
1696 return ret;
1697}
1698
1699PyObject *
1700PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1701 PyObject *locals, int closeit, PyCompilerFlags *flags)
1702{
1703 PyObject *ret;
1704 mod_ty mod;
1705 PyArena *arena = PyArena_New();
1706 if (arena == NULL((void *)0))
1707 return NULL((void *)0);
1708
1709 mod = PyParser_ASTFromFile(fp, filename, NULL((void *)0), start, 0, 0,
1710 flags, NULL((void *)0), arena);
1711 if (closeit)
1712 fclose(fp);
1713 if (mod == NULL((void *)0)) {
1714 PyArena_Free(arena);
1715 return NULL((void *)0);
1716 }
1717 ret = run_mod(mod, filename, globals, locals, flags, arena);
1718 PyArena_Free(arena);
1719 return ret;
1720}
1721
1722static void
1723flush_io(void)
1724{
1725 PyObject *f, *r;
1726 PyObject *type, *value, *traceback;
1727
1728 /* Save the current exception */
1729 PyErr_Fetch(&type, &value, &traceback);
1730
1731 f = PySys_GetObject("stderr");
1732 if (f != NULL((void *)0)) {
1733 r = PyObject_CallMethod(f, "flush", "");
1734 if (r)
1735 Py_DECREF(r)do { if (_Py_RefTotal-- , --((PyObject*)(r))->ob_refcnt !=
0) { if (((PyObject*)r)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1735, (PyObject *)(r)); } else _Py_Dealloc
((PyObject *)(r)); } while (0)
;
1736 else
1737 PyErr_Clear();
1738 }
1739 f = PySys_GetObject("stdout");
1740 if (f != NULL((void *)0)) {
1741 r = PyObject_CallMethod(f, "flush", "");
1742 if (r)
1743 Py_DECREF(r)do { if (_Py_RefTotal-- , --((PyObject*)(r))->ob_refcnt !=
0) { if (((PyObject*)r)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1743, (PyObject *)(r)); } else _Py_Dealloc
((PyObject *)(r)); } while (0)
;
1744 else
1745 PyErr_Clear();
1746 }
1747
1748 PyErr_Restore(type, value, traceback);
1749}
1750
1751static PyObject *
1752run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
1753 PyCompilerFlags *flags, PyArena *arena)
1754{
1755 PyCodeObject *co;
1756 PyObject *v;
1757 co = PyAST_Compile(mod, filename, flags, arena)PyAST_CompileEx(mod, filename, flags, -1, arena);
1758 if (co == NULL((void *)0))
1759 return NULL((void *)0);
1760 v = PyEval_EvalCode((PyObject*)co, globals, locals);
1761 Py_DECREF(co)do { if (_Py_RefTotal-- , --((PyObject*)(co))->ob_refcnt !=
0) { if (((PyObject*)co)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1761, (PyObject *)(co)); } else _Py_Dealloc
((PyObject *)(co)); } while (0)
;
1762 return v;
1763}
1764
1765static PyObject *
1766run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
1767 PyObject *locals, PyCompilerFlags *flags)
1768{
1769 PyCodeObject *co;
1770 PyObject *v;
1771 long magic;
1772 long PyImport_GetMagicNumber(void);
1773
1774 magic = PyMarshal_ReadLongFromFile(fp);
1775 if (magic != PyImport_GetMagicNumber()) {
1776 PyErr_SetString(PyExc_RuntimeError,
1777 "Bad magic number in .pyc file");
1778 return NULL((void *)0);
1779 }
1780 (void) PyMarshal_ReadLongFromFile(fp);
1781 v = PyMarshal_ReadLastObjectFromFile(fp);
1782 fclose(fp);
1783 if (v == NULL((void *)0) || !PyCode_Check(v)((((PyObject*)(v))->ob_type) == &PyCode_Type)) {
1784 Py_XDECREF(v)do { if ((v) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(v))->ob_refcnt != 0) { if (((PyObject*)v)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 1784
, (PyObject *)(v)); } else _Py_Dealloc((PyObject *)(v)); } while
(0); } while (0)
;
1785 PyErr_SetString(PyExc_RuntimeError,
1786 "Bad code object in .pyc file");
1787 return NULL((void *)0);
1788 }
1789 co = (PyCodeObject *)v;
1790 v = PyEval_EvalCode((PyObject*)co, globals, locals);
1791 if (v && flags)
1792 flags->cf_flags |= (co->co_flags & PyCF_MASK(0x2000 | 0x4000 | 0x8000 | 0x10000 | 0x20000 | 0x40000));
1793 Py_DECREF(co)do { if (_Py_RefTotal-- , --((PyObject*)(co))->ob_refcnt !=
0) { if (((PyObject*)co)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 1793, (PyObject *)(co)); } else _Py_Dealloc
((PyObject *)(co)); } while (0)
;
1794 return v;
1795}
1796
1797PyObject *
1798Py_CompileStringExFlags(const char *str, const char *filename, int start,
1799 PyCompilerFlags *flags, int optimize)
1800{
1801 PyCodeObject *co;
1802 mod_ty mod;
1803 PyArena *arena = PyArena_New();
1804 if (arena == NULL((void *)0))
1805 return NULL((void *)0);
1806
1807 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1808 if (mod == NULL((void *)0)) {
1809 PyArena_Free(arena);
1810 return NULL((void *)0);
1811 }
1812 if (flags && (flags->cf_flags & PyCF_ONLY_AST0x0400)) {
1813 PyObject *result = PyAST_mod2obj(mod);
1814 PyArena_Free(arena);
1815 return result;
1816 }
1817 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
1818 PyArena_Free(arena);
1819 return (PyObject *)co;
1820}
1821
1822/* For use in Py_LIMITED_API */
1823#undef Py_CompileString
1824PyObject *
1825PyCompileString(const char *str, const char *filename, int start)
1826{
1827 return Py_CompileStringFlags(str, filename, start, NULL((void *)0));
1828}
1829
1830struct symtable *
1831Py_SymtableString(const char *str, const char *filename, int start)
1832{
1833 struct symtable *st;
1834 mod_ty mod;
1835 PyCompilerFlags flags;
1836 PyArena *arena = PyArena_New();
1837 if (arena == NULL((void *)0))
1838 return NULL((void *)0);
1839
1840 flags.cf_flags = 0;
1841 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1842 if (mod == NULL((void *)0)) {
1843 PyArena_Free(arena);
1844 return NULL((void *)0);
1845 }
1846 st = PySymtable_Build(mod, filename, 0);
1847 PyArena_Free(arena);
1848 return st;
1849}
1850
1851/* Preferred access to parser is through AST. */
1852mod_ty
1853PyParser_ASTFromString(const char *s, const char *filename, int start,
1854 PyCompilerFlags *flags, PyArena *arena)
1855{
1856 mod_ty mod;
1857 PyCompilerFlags localflags;
1858 perrdetail err;
1859 int iflags = PARSER_FLAGS(flags);
1860
1861 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1862 &_PyParser_Grammar, start, &err,
1863 &iflags);
1864 if (flags == NULL((void *)0)) {
1865 localflags.cf_flags = 0;
1866 flags = &localflags;
1867 }
1868 if (n) {
1869 flags->cf_flags |= iflags & PyCF_MASK(0x2000 | 0x4000 | 0x8000 | 0x10000 | 0x20000 | 0x40000);
1870 mod = PyAST_FromNode(n, flags, filename, arena);
1871 PyNode_Free(n);
1872 return mod;
1873 }
1874 else {
1875 err_input(&err);
1876 return NULL((void *)0);
1877 }
1878}
1879
1880mod_ty
1881PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1882 int start, char *ps1,
1883 char *ps2, PyCompilerFlags *flags, int *errcode,
1884 PyArena *arena)
1885{
1886 mod_ty mod;
1887 PyCompilerFlags localflags;
1888 perrdetail err;
1889 int iflags = PARSER_FLAGS(flags);
1890
1891 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1892 &_PyParser_Grammar,
1893 start, ps1, ps2, &err, &iflags);
1894 if (flags == NULL((void *)0)) {
1895 localflags.cf_flags = 0;
1896 flags = &localflags;
1897 }
1898 if (n) {
1899 flags->cf_flags |= iflags & PyCF_MASK(0x2000 | 0x4000 | 0x8000 | 0x10000 | 0x20000 | 0x40000);
1900 mod = PyAST_FromNode(n, flags, filename, arena);
1901 PyNode_Free(n);
1902 return mod;
1903 }
1904 else {
1905 err_input(&err);
1906 if (errcode)
1907 *errcode = err.error;
1908 return NULL((void *)0);
1909 }
1910}
1911
1912/* Simplified interface to parsefile -- return node or set exception */
1913
1914node *
1915PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
1916{
1917 perrdetail err;
1918 node *n = PyParser_ParseFileFlags(fp, filename, NULL((void *)0),
1919 &_PyParser_Grammar,
1920 start, NULL((void *)0), NULL((void *)0), &err, flags);
1921 if (n == NULL((void *)0))
1922 err_input(&err);
1923
1924 return n;
1925}
1926
1927/* Simplified interface to parsestring -- return node or set exception */
1928
1929node *
1930PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
1931{
1932 perrdetail err;
1933 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1934 start, &err, flags);
1935 if (n == NULL((void *)0))
1936 err_input(&err);
1937 return n;
1938}
1939
1940node *
1941PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
1942 int start, int flags)
1943{
1944 perrdetail err;
1945 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1946 &_PyParser_Grammar, start, &err, flags);
1947 if (n == NULL((void *)0))
1948 err_input(&err);
1949 return n;
1950}
1951
1952node *
1953PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
1954{
1955 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
1956}
1957
1958/* May want to move a more generalized form of this to parsetok.c or
1959 even parser modules. */
1960
1961void
1962PyParser_SetError(perrdetail *err)
1963{
1964 err_input(err);
1965}
1966
1967/* Set the error appropriate to the given input error code (see errcode.h) */
1968
1969static void
1970err_input(perrdetail *err)
1971{
1972 PyObject *v, *w, *errtype, *errtext;
1973 PyObject *msg_obj = NULL((void *)0);
1974 PyObject *filename;
1975 char *msg = NULL((void *)0);
1976
1977 errtype = PyExc_SyntaxError;
1978 switch (err->error) {
1979 case E_ERROR17:
1980 return;
1981 case E_SYNTAX14:
1982 errtype = PyExc_IndentationError;
1983 if (err->expected == INDENT5)
1984 msg = "expected an indented block";
1985 else if (err->token == INDENT5)
1986 msg = "unexpected indent";
1987 else if (err->token == DEDENT6)
1988 msg = "unexpected unindent";
1989 else {
1990 errtype = PyExc_SyntaxError;
1991 msg = "invalid syntax";
1992 }
1993 break;
1994 case E_TOKEN13:
1995 msg = "invalid token";
1996 break;
1997 case E_EOFS23:
1998 msg = "EOF while scanning triple-quoted string literal";
1999 break;
2000 case E_EOLS24:
2001 msg = "EOL while scanning string literal";
2002 break;
2003 case E_INTR12:
2004 if (!PyErr_Occurred())
2005 PyErr_SetNone(PyExc_KeyboardInterrupt);
2006 goto cleanup;
2007 case E_NOMEM15:
2008 PyErr_NoMemory();
2009 goto cleanup;
2010 case E_EOF11:
2011 msg = "unexpected EOF while parsing";
2012 break;
2013 case E_TABSPACE18:
2014 errtype = PyExc_TabError;
2015 msg = "inconsistent use of tabs and spaces in indentation";
2016 break;
2017 case E_OVERFLOW19:
2018 msg = "expression too long";
2019 break;
2020 case E_DEDENT21:
2021 errtype = PyExc_IndentationError;
2022 msg = "unindent does not match any outer indentation level";
2023 break;
2024 case E_TOODEEP20:
2025 errtype = PyExc_IndentationError;
2026 msg = "too many levels of indentation";
2027 break;
2028 case E_DECODE22: {
2029 PyObject *type, *value, *tb;
2030 PyErr_Fetch(&type, &value, &tb);
2031 msg = "unknown decode error";
2032 if (value != NULL((void *)0))
2033 msg_obj = PyObject_Str(value);
2034 Py_XDECREF(type)do { if ((type) == ((void *)0)) ; else do { if (_Py_RefTotal--
, --((PyObject*)(type))->ob_refcnt != 0) { if (((PyObject
*)type)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 2034, (PyObject *)(type)); } else _Py_Dealloc((PyObject *)(
type)); } while (0); } while (0)
;
2035 Py_XDECREF(value)do { if ((value) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(value))->ob_refcnt != 0) { if (((PyObject
*)value)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 2035, (PyObject *)(value)); } else _Py_Dealloc((PyObject *)
(value)); } while (0); } while (0)
;
2036 Py_XDECREF(tb)do { if ((tb) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(tb))->ob_refcnt != 0) { if (((PyObject*)tb
)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 2036, (PyObject *)(tb)); } else _Py_Dealloc((PyObject *)(tb
)); } while (0); } while (0)
;
2037 break;
2038 }
2039 case E_LINECONT25:
2040 msg = "unexpected character after line continuation character";
2041 break;
2042
2043 case E_IDENTIFIER26:
2044 msg = "invalid character in identifier";
2045 break;
2046 default:
2047 fprintf(stderr__stderrp, "error=%d\n", err->error);
2048 msg = "unknown parsing error";
2049 break;
2050 }
2051 /* err->text may not be UTF-8 in case of decoding errors.
2052 Explicitly convert to an object. */
2053 if (!err->text) {
2054 errtext = Py_None(&_Py_NoneStruct);
2055 Py_INCREF(Py_None)( _Py_RefTotal++ , ((PyObject*)((&_Py_NoneStruct)))->ob_refcnt
++)
;
2056 } else {
2057 errtext = PyUnicode_DecodeUTF8PyUnicodeUCS2_DecodeUTF8(err->text, strlen(err->text),
2058 "replace");
2059 }
2060 if (err->filename != NULL((void *)0))
2061 filename = PyUnicode_DecodeFSDefaultPyUnicodeUCS2_DecodeFSDefault(err->filename);
2062 else {
2063 Py_INCREF(Py_None)( _Py_RefTotal++ , ((PyObject*)((&_Py_NoneStruct)))->ob_refcnt
++)
;
2064 filename = Py_None(&_Py_NoneStruct);
2065 }
2066 if (filename != NULL((void *)0))
2067 v = Py_BuildValue("(NiiN)", filename,
2068 err->lineno, err->offset, errtext);
2069 else
2070 v = NULL((void *)0);
2071 if (v != NULL((void *)0)) {
2072 if (msg_obj)
2073 w = Py_BuildValue("(OO)", msg_obj, v);
2074 else
2075 w = Py_BuildValue("(sO)", msg, v);
2076 } else
2077 w = NULL((void *)0);
2078 Py_XDECREF(v)do { if ((v) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(v))->ob_refcnt != 0) { if (((PyObject*)v)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 2078
, (PyObject *)(v)); } else _Py_Dealloc((PyObject *)(v)); } while
(0); } while (0)
;
2079 PyErr_SetObject(errtype, w);
2080 Py_XDECREF(w)do { if ((w) == ((void *)0)) ; else do { if (_Py_RefTotal-- ,
--((PyObject*)(w))->ob_refcnt != 0) { if (((PyObject*)w)->
ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c", 2080
, (PyObject *)(w)); } else _Py_Dealloc((PyObject *)(w)); } while
(0); } while (0)
;
2081cleanup:
2082 Py_XDECREF(msg_obj)do { if ((msg_obj) == ((void *)0)) ; else do { if (_Py_RefTotal
-- , --((PyObject*)(msg_obj))->ob_refcnt != 0) { if (((PyObject
*)msg_obj)->ob_refcnt < 0) _Py_NegativeRefcount("Python/pythonrun.c"
, 2082, (PyObject *)(msg_obj)); } else _Py_Dealloc((PyObject *
)(msg_obj)); } while (0); } while (0)
;
2083 if (err->text != NULL((void *)0)) {
2084 PyObject_FREE_PyObject_DebugFree(err->text);
2085 err->text = NULL((void *)0);
2086 }
2087}
2088
2089/* Print fatal error message and abort */
2090
2091void
2092Py_FatalError(const char *msg)
2093{
2094 fprintf(stderr__stderrp, "Fatal Python error: %s\n", msg);
2095 fflush(stderr__stderrp); /* it helps in Windows debug build */
2096 if (PyErr_Occurred()) {
2097 PyErr_PrintEx(0);
2098 }
2099#ifdef MS_WINDOWS
2100 {
2101 size_t len = strlen(msg);
2102 WCHAR* buffer;
2103 size_t i;
2104
2105 /* Convert the message to wchar_t. This uses a simple one-to-one
2106 conversion, assuming that the this error message actually uses ASCII
2107 only. If this ceases to be true, we will have to convert. */
2108 buffer = alloca( (len+1) * (sizeof *buffer))__builtin_alloca((len+1) * (sizeof *buffer));
2109 for( i=0; i<=len; ++i)
2110 buffer[i] = msg[i];
2111 OutputDebugStringW(L"Fatal Python error: ");
2112 OutputDebugStringW(buffer);
2113 OutputDebugStringW(L"\n");
2114 }
2115#ifdef _DEBUG
2116 DebugBreak();
2117#endif
2118#endif /* MS_WINDOWS */
2119 abort();
2120}
2121
2122/* Clean up and exit */
2123
2124#ifdef WITH_THREAD1
2125#include "pythread.h"
2126#endif
2127
2128static void (*pyexitfunc)(void) = NULL((void *)0);
2129/* For the atexit module. */
2130void _Py_PyAtExit(void (*func)(void))
2131{
2132 pyexitfunc = func;
2133}
2134
2135static void
2136call_py_exitfuncs(void)
2137{
2138 if (pyexitfunc == NULL((void *)0))
2139 return;
2140
2141 (*pyexitfunc)();
2142 PyErr_Clear();
2143}
2144
2145/* Wait until threading._shutdown completes, provided
2146 the threading module was imported in the first place.
2147 The shutdown routine will wait until all non-daemon
2148 "threading" threads have completed. */
2149static void
2150wait_for_thread_shutdown(void)
2151{
2152#ifdef WITH_THREAD1
2153 PyObject *result;
2154 PyThreadState *tstate = PyThreadState_GET()PyThreadState_Get();
2155 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2156 "threading");
2157 if (threading == NULL((void *)0)) {
2158 /* threading not imported */
2159 PyErr_Clear();
2160 return;
2161 }
2162 result = PyObject_CallMethod(threading, "_shutdown", "");
2163 if (result == NULL((void *)0)) {
2164 PyErr_WriteUnraisable(threading);
2165 }
2166 else {
2167 Py_DECREF(result)do { if (_Py_RefTotal-- , --((PyObject*)(result))->ob_refcnt
!= 0) { if (((PyObject*)result)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 2167, (PyObject *)(result)); } else _Py_Dealloc
((PyObject *)(result)); } while (0)
;
2168 }
2169 Py_DECREF(threading)do { if (_Py_RefTotal-- , --((PyObject*)(threading))->ob_refcnt
!= 0) { if (((PyObject*)threading)->ob_refcnt < 0) _Py_NegativeRefcount
("Python/pythonrun.c", 2169, (PyObject *)(threading)); } else
_Py_Dealloc((PyObject *)(threading)); } while (0)
;
2170#endif
2171}
2172
2173#define NEXITFUNCS32 32
2174static void (*exitfuncs[NEXITFUNCS32])(void);
2175static int nexitfuncs = 0;
2176
2177int Py_AtExit(void (*func)(void))
2178{
2179 if (nexitfuncs >= NEXITFUNCS32)
2180 return -1;
2181 exitfuncs[nexitfuncs++] = func;
2182 return 0;
2183}
2184
2185static void
2186call_ll_exitfuncs(void)
2187{
2188 while (nexitfuncs > 0)
2189 (*exitfuncs[--nexitfuncs])();
2190
2191 fflush(stdout__stdoutp);
2192 fflush(stderr__stderrp);
2193}
2194
2195void
2196Py_Exit(int sts)
2197{
2198 Py_Finalize();
2199
2200 exit(sts);
2201}
2202
2203static void
2204initsigs(void)
2205{
2206#ifdef SIGPIPE13
2207 PyOS_setsig(SIGPIPE13, SIG_IGN(void (*)(int))1);
2208#endif
2209#ifdef SIGXFZ
2210 PyOS_setsig(SIGXFZ, SIG_IGN(void (*)(int))1);
2211#endif
2212#ifdef SIGXFSZ25
2213 PyOS_setsig(SIGXFSZ25, SIG_IGN(void (*)(int))1);
2214#endif
2215 PyOS_InitInterrupts(); /* May imply initsignal() */
2216}
2217
2218
2219/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2220 *
2221 * All of the code in this function must only use async-signal-safe functions,
2222 * listed at `man 7 signal` or
2223 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2224 */
2225void
2226_Py_RestoreSignals(void)
2227{
2228#ifdef SIGPIPE13
2229 PyOS_setsig(SIGPIPE13, SIG_DFL(void (*)(int))0);
2230#endif
2231#ifdef SIGXFZ
2232 PyOS_setsig(SIGXFZ, SIG_DFL(void (*)(int))0);
2233#endif
2234#ifdef SIGXFSZ25
2235 PyOS_setsig(SIGXFSZ25, SIG_DFL(void (*)(int))0);
2236#endif
2237}
2238
2239
2240/*
2241 * The file descriptor fd is considered ``interactive'' if either
2242 * a) isatty(fd) is TRUE, or
2243 * b) the -i flag was given, and the filename associated with
2244 * the descriptor is NULL or "<stdin>" or "???".
2245 */
2246int
2247Py_FdIsInteractive(FILE *fp, const char *filename)
2248{
2249 if (isatty((int)fileno(fp)))
2250 return 1;
2251 if (!Py_InteractiveFlag)
2252 return 0;
2253 return (filename == NULL((void *)0)) ||
2254 (strcmp(filename, "<stdin>") == 0) ||
2255 (strcmp(filename, "???") == 0);
2256}
2257
2258
2259#if defined(USE_STACKCHECK)
2260#if defined(WIN32) && defined(_MSC_VER)
2261
2262/* Stack checking for Microsoft C */
2263
2264#include <malloc.h>
2265#include <excpt.h>
2266
2267/*
2268 * Return non-zero when we run out of memory on the stack; zero otherwise.
2269 */
2270int
2271PyOS_CheckStack(void)
2272{
2273 __try {
2274 /* alloca throws a stack overflow exception if there's
2275 not enough space left on the stack */
2276 alloca(PYOS_STACK_MARGIN * sizeof(void*))__builtin_alloca(2048 * sizeof(void*));
2277 return 0;
2278 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2279 EXCEPTION_EXECUTE_HANDLER :
2280 EXCEPTION_CONTINUE_SEARCH) {
2281 int errcode = _resetstkoflw();
2282 if (errcode == 0)
2283 {
2284 Py_FatalError("Could not reset the stack!");
2285 }
2286 }
2287 return 1;
2288}
2289
2290#endif /* WIN32 && _MSC_VER */
2291
2292/* Alternate implementations can be added here... */
2293
2294#endif /* USE_STACKCHECK */
2295
2296
2297/* Wrappers around sigaction() or signal(). */
2298
2299PyOS_sighandler_t
2300PyOS_getsig(int sig)
2301{
2302#ifdef HAVE_SIGACTION1
2303 struct sigaction context;
2304 if (sigaction(sig, NULL((void *)0), &context) == -1)
2305 return SIG_ERR((void (*)(int))-1);
2306 return context.sa_handler__sigaction_u.__sa_handler;
2307#else
2308 PyOS_sighandler_t handler;
2309/* Special signal handling for the secure CRT in Visual Studio 2005 */
2310#if defined(_MSC_VER) && _MSC_VER >= 1400
2311 switch (sig) {
2312 /* Only these signals are valid */
2313 case SIGINT2:
2314 case SIGILL4:
2315 case SIGFPE8:
2316 case SIGSEGV11:
2317 case SIGTERM15:
2318 case SIGBREAK:
2319 case SIGABRT6:
2320 break;
2321 /* Don't call signal() with other values or it will assert */
2322 default:
2323 return SIG_ERR((void (*)(int))-1);
2324 }
2325#endif /* _MSC_VER && _MSC_VER >= 1400 */
2326 handler = signal(sig, SIG_IGN(void (*)(int))1);
2327 if (handler != SIG_ERR((void (*)(int))-1))
2328 signal(sig, handler);
2329 return handler;
2330#endif
2331}
2332
2333/*
2334 * All of the code in this function must only use async-signal-safe functions,
2335 * listed at `man 7 signal` or
2336 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2337 */
2338PyOS_sighandler_t
2339PyOS_setsig(int sig, PyOS_sighandler_t handler)
2340{
2341#ifdef HAVE_SIGACTION1
2342 /* Some code in Modules/signalmodule.c depends on sigaction() being
2343 * used here if HAVE_SIGACTION is defined. Fix that if this code
2344 * changes to invalidate that assumption.
2345 */
2346 struct sigaction context, ocontext;
2347 context.sa_handler__sigaction_u.__sa_handler = handler;
2348 sigemptyset(&context.sa_mask)(*(&context.sa_mask) = 0, 0);
2349 context.sa_flags = 0;
2350 if (sigaction(sig, &context, &ocontext) == -1)
2351 return SIG_ERR((void (*)(int))-1);
2352 return ocontext.sa_handler__sigaction_u.__sa_handler;
2353#else
2354 PyOS_sighandler_t oldhandler;
2355 oldhandler = signal(sig, handler);
2356#ifdef HAVE_SIGINTERRUPT1
2357 siginterrupt(sig, 1);
2358#endif
2359 return oldhandler;
2360#endif
2361}
2362
2363/* Deprecated C API functions still provided for binary compatiblity */
2364
2365#undef PyParser_SimpleParseFile
2366PyAPI_FUNC(node *)node *
2367PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2368{
2369 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2370}
2371
2372#undef PyParser_SimpleParseString
2373PyAPI_FUNC(node *)node *
2374PyParser_SimpleParseString(const char *str, int start)
2375{
2376 return PyParser_SimpleParseStringFlags(str, start, 0);
2377}
2378
2379#undef PyRun_AnyFile
2380PyAPI_FUNC(int)int
2381PyRun_AnyFile(FILE *fp, const char *name)
2382{
2383 return PyRun_AnyFileExFlags(fp, name, 0, NULL((void *)0));
2384}
2385
2386#undef PyRun_AnyFileEx
2387PyAPI_FUNC(int)int
2388PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2389{
2390 return PyRun_AnyFileExFlags(fp, name, closeit, NULL((void *)0));
2391}
2392
2393#undef PyRun_AnyFileFlags
2394PyAPI_FUNC(int)int
2395PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2396{
2397 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2398}
2399
2400#undef PyRun_File
2401PyAPI_FUNC(PyObject *)PyObject *
2402PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2403{
2404 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL((void *)0));
2405}
2406
2407#undef PyRun_FileEx
2408PyAPI_FUNC(PyObject *)PyObject *
2409PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2410{
2411 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL((void *)0));
2412}
2413
2414#undef PyRun_FileFlags
2415PyAPI_FUNC(PyObject *)PyObject *
2416PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2417 PyCompilerFlags *flags)
2418{
2419 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
2420}
2421
2422#undef PyRun_SimpleFile
2423PyAPI_FUNC(int)int
2424PyRun_SimpleFile(FILE *f, const char *p)
2425{
2426 return PyRun_SimpleFileExFlags(f, p, 0, NULL((void *)0));
2427}
2428
2429#undef PyRun_SimpleFileEx
2430PyAPI_FUNC(int)int
2431PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2432{
2433 return PyRun_SimpleFileExFlags(f, p, c, NULL((void *)0));
2434}
2435
2436
2437#undef PyRun_String
2438PyAPI_FUNC(PyObject *)PyObject *
2439PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2440{
2441 return PyRun_StringFlags(str, s, g, l, NULL((void *)0));
2442}
2443
2444#undef PyRun_SimpleString
2445PyAPI_FUNC(int)int
2446PyRun_SimpleString(const char *s)
2447{
2448 return PyRun_SimpleStringFlags(s, NULL((void *)0));
2449}
2450
2451#undef Py_CompileString
2452PyAPI_FUNC(PyObject *)PyObject *
2453Py_CompileString(const char *str, const char *p, int s)
2454{
2455 return Py_CompileStringExFlags(str, p, s, NULL((void *)0), -1);
2456}
2457
2458#undef Py_CompileStringFlags
2459PyAPI_FUNC(PyObject *)PyObject *
2460Py_CompileStringFlags(const char *str, const char *p, int s,
2461 PyCompilerFlags *flags)
2462{
2463 return Py_CompileStringExFlags(str, p, s, flags, -1);
2464}
2465
2466#undef PyRun_InteractiveOne
2467PyAPI_FUNC(int)int
2468PyRun_InteractiveOne(FILE *f, const char *p)
2469{
2470 return PyRun_InteractiveOneFlags(f, p, NULL((void *)0));
2471}
2472
2473#undef PyRun_InteractiveLoop
2474PyAPI_FUNC(int)int
2475PyRun_InteractiveLoop(FILE *f, const char *p)
2476{
2477 return PyRun_InteractiveLoopFlags(f, p, NULL((void *)0));
2478}
2479
2480#ifdef __cplusplus
2481}
2482#endif