comparison Python/pythonrun.c @ 61466:cab14be0ada1

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