comparison Python/pythonrun.c @ 61467:f197407bdba2 3.1

Recorded merge of revisions 81032 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/py3k ................ r81032 | antoine.pitrou | 2010-05-09 17:52:27 +0200 (dim., 09 mai 2010) | 9 lines 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 16:14:21 +0000
parents 677511edf05c
children 9f62f5865b44
comparison
equal deleted inserted replaced
61459:f8c19c5f5dd2 61467:f197407bdba2
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 #ifdef HAVE_SETLOCALE 183 #ifdef 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, *f; 715 PyObject *m, *f;
716 m = PyImport_ImportModule("site"); 716 m = PyImport_ImportModule("site");
717 if (m == NULL) { 717 if (m == NULL) {
718 f = PySys_GetObject("stderr"); 718 f = PySys_GetObject("stderr");
719 if (f == NULL || f == Py_None) 719 if (f == NULL || f == Py_None)
720 return; 720 return;
721 if (Py_VerboseFlag) { 721 if (Py_VerboseFlag) {
722 PyFile_WriteString( 722 PyFile_WriteString(
723 "'import site' failed; traceback:\n", f); 723 "'import site' failed; traceback:\n", f);
724 PyErr_Print(); 724 PyErr_Print();
725 } 725 }
726 else { 726 else {
727 PyFile_WriteString( 727 PyFile_WriteString(
728 "'import site' failed; use -v for traceback\n", f); 728 "'import site' failed; use -v for traceback\n", f);
729 PyErr_Clear(); 729 PyErr_Clear();
730 } 730 }
731 } 731 }
732 else { 732 else {
733 Py_DECREF(m); 733 Py_DECREF(m);
734 } 734 }
735 } 735 }
736 736
737 static PyObject* 737 static PyObject*
738 create_stdio(PyObject* io, 738 create_stdio(PyObject* io,
739 int fd, int write_mode, char* name, 739 int fd, int write_mode, char* name,
740 char* encoding, char* errors) 740 char* encoding, char* errors)
741 { 741 {
742 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; 742 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
743 const char* mode; 743 const char* mode;
744 PyObject *line_buffering; 744 PyObject *line_buffering;
745 int buffering, isatty; 745 int buffering, isatty;
746 746
747 /* stdin is always opened in buffered mode, first because it shouldn't 747 /* stdin is always opened in buffered mode, first because it shouldn't
748 make a difference in common use cases, second because TextIOWrapper 748 make a difference in common use cases, second because TextIOWrapper
749 depends on the presence of a read1() method which only exists on 749 depends on the presence of a read1() method which only exists on
750 buffered streams. 750 buffered streams.
751 */ 751 */
752 if (Py_UnbufferedStdioFlag && write_mode) 752 if (Py_UnbufferedStdioFlag && write_mode)
753 buffering = 0; 753 buffering = 0;
754 else 754 else
755 buffering = -1; 755 buffering = -1;
756 if (write_mode) 756 if (write_mode)
757 mode = "wb"; 757 mode = "wb";
758 else 758 else
759 mode = "rb"; 759 mode = "rb";
760 buf = PyObject_CallMethod(io, "open", "isiOOOi", 760 buf = PyObject_CallMethod(io, "open", "isiOOOi",
761 fd, mode, buffering, 761 fd, mode, buffering,
762 Py_None, Py_None, Py_None, 0); 762 Py_None, Py_None, Py_None, 0);
763 if (buf == NULL) 763 if (buf == NULL)
764 goto error; 764 goto error;
765 765
766 if (buffering) { 766 if (buffering) {
767 raw = PyObject_GetAttrString(buf, "raw"); 767 raw = PyObject_GetAttrString(buf, "raw");
768 if (raw == NULL) 768 if (raw == NULL)
769 goto error; 769 goto error;
770 } 770 }
771 else { 771 else {
772 raw = buf; 772 raw = buf;
773 Py_INCREF(raw); 773 Py_INCREF(raw);
774 } 774 }
775 775
776 text = PyUnicode_FromString(name); 776 text = PyUnicode_FromString(name);
777 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0) 777 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
778 goto error; 778 goto error;
779 res = PyObject_CallMethod(raw, "isatty", ""); 779 res = PyObject_CallMethod(raw, "isatty", "");
780 if (res == NULL) 780 if (res == NULL)
781 goto error; 781 goto error;
782 isatty = PyObject_IsTrue(res); 782 isatty = PyObject_IsTrue(res);
783 Py_DECREF(res); 783 Py_DECREF(res);
784 if (isatty == -1) 784 if (isatty == -1)
785 goto error; 785 goto error;
786 if (isatty || Py_UnbufferedStdioFlag) 786 if (isatty || Py_UnbufferedStdioFlag)
787 line_buffering = Py_True; 787 line_buffering = Py_True;
788 else 788 else
789 line_buffering = Py_False; 789 line_buffering = Py_False;
790 790
791 Py_CLEAR(raw); 791 Py_CLEAR(raw);
792 Py_CLEAR(text); 792 Py_CLEAR(text);
793 793
794 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO", 794 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
795 buf, encoding, errors, 795 buf, encoding, errors,
796 "\n", line_buffering); 796 "\n", line_buffering);
797 Py_CLEAR(buf); 797 Py_CLEAR(buf);
798 if (stream == NULL) 798 if (stream == NULL)
799 goto error; 799 goto error;
800 800
801 if (write_mode) 801 if (write_mode)
802 mode = "w"; 802 mode = "w";
803 else 803 else
804 mode = "r"; 804 mode = "r";
805 text = PyUnicode_FromString(mode); 805 text = PyUnicode_FromString(mode);
806 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0) 806 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
807 goto error; 807 goto error;
808 Py_CLEAR(text); 808 Py_CLEAR(text);
809 return stream; 809 return stream;
810 810
811 error: 811 error:
812 Py_XDECREF(buf); 812 Py_XDECREF(buf);
813 Py_XDECREF(stream); 813 Py_XDECREF(stream);
814 Py_XDECREF(text); 814 Py_XDECREF(text);
815 Py_XDECREF(raw); 815 Py_XDECREF(raw);
816 return NULL; 816 return NULL;
817 } 817 }
818 818
819 /* Initialize sys.stdin, stdout, stderr and builtins.open */ 819 /* Initialize sys.stdin, stdout, stderr and builtins.open */
820 static int 820 static int
821 initstdio(void) 821 initstdio(void)
822 { 822 {
823 PyObject *iomod = NULL, *wrapper; 823 PyObject *iomod = NULL, *wrapper;
824 PyObject *bimod = NULL; 824 PyObject *bimod = NULL;
825 PyObject *m; 825 PyObject *m;
826 PyObject *std = NULL; 826 PyObject *std = NULL;
827 int status = 0, fd; 827 int status = 0, fd;
828 PyObject * encoding_attr; 828 PyObject * encoding_attr;
829 char *encoding = NULL, *errors; 829 char *encoding = NULL, *errors;
830 830
831 /* Hack to avoid a nasty recursion issue when Python is invoked 831 /* Hack to avoid a nasty recursion issue when Python is invoked
832 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ 832 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
833 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { 833 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
834 goto error; 834 goto error;
835 } 835 }
836 Py_DECREF(m); 836 Py_DECREF(m);
837 837
838 if (!(m = PyImport_ImportModule("encodings.latin_1"))) { 838 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
839 goto error; 839 goto error;
840 } 840 }
841 Py_DECREF(m); 841 Py_DECREF(m);
842 842
843 if (!(bimod = PyImport_ImportModule("builtins"))) { 843 if (!(bimod = PyImport_ImportModule("builtins"))) {
844 goto error; 844 goto error;
845 } 845 }
846 846
847 if (!(iomod = PyImport_ImportModule("io"))) { 847 if (!(iomod = PyImport_ImportModule("io"))) {
848 goto error; 848 goto error;
849 } 849 }
850 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { 850 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
851 goto error; 851 goto error;
852 } 852 }
853 853
854 /* Set builtins.open */ 854 /* Set builtins.open */
855 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { 855 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
856 goto error; 856 goto error;
857 } 857 }
858 858
859 encoding = Py_GETENV("PYTHONIOENCODING"); 859 encoding = Py_GETENV("PYTHONIOENCODING");
860 errors = NULL; 860 errors = NULL;
861 if (encoding) { 861 if (encoding) {
862 encoding = strdup(encoding); 862 encoding = strdup(encoding);
863 errors = strchr(encoding, ':'); 863 errors = strchr(encoding, ':');
864 if (errors) { 864 if (errors) {
865 *errors = '\0'; 865 *errors = '\0';
866 errors++; 866 errors++;
867 } 867 }
868 } 868 }
869 869
870 /* Set sys.stdin */ 870 /* Set sys.stdin */
871 fd = fileno(stdin); 871 fd = fileno(stdin);
872 /* Under some conditions stdin, stdout and stderr may not be connected 872 /* Under some conditions stdin, stdout and stderr may not be connected
873 * and fileno() may point to an invalid file descriptor. For example 873 * and fileno() may point to an invalid file descriptor. For example
874 * GUI apps don't have valid standard streams by default. 874 * GUI apps don't have valid standard streams by default.
875 */ 875 */
876 if (fd < 0) { 876 if (fd < 0) {
877 #ifdef MS_WINDOWS 877 #ifdef MS_WINDOWS
878 std = Py_None; 878 std = Py_None;
879 Py_INCREF(std); 879 Py_INCREF(std);
880 #else 880 #else
881 goto error; 881 goto error;
882 #endif 882 #endif
883 } 883 }
884 else { 884 else {
885 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors); 885 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
886 if (std == NULL) 886 if (std == NULL)
887 goto error; 887 goto error;
888 } /* if (fd < 0) */ 888 } /* if (fd < 0) */
889 PySys_SetObject("__stdin__", std); 889 PySys_SetObject("__stdin__", std);
890 PySys_SetObject("stdin", std); 890 PySys_SetObject("stdin", std);
891 Py_DECREF(std); 891 Py_DECREF(std);
892 892
893 /* Set sys.stdout */ 893 /* Set sys.stdout */
894 fd = fileno(stdout); 894 fd = fileno(stdout);
895 if (fd < 0) { 895 if (fd < 0) {
896 #ifdef MS_WINDOWS 896 #ifdef MS_WINDOWS
897 std = Py_None; 897 std = Py_None;
898 Py_INCREF(std); 898 Py_INCREF(std);
899 #else 899 #else
900 goto error; 900 goto error;
901 #endif 901 #endif
902 } 902 }
903 else { 903 else {
904 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors); 904 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
905 if (std == NULL) 905 if (std == NULL)
906 goto error; 906 goto error;
907 } /* if (fd < 0) */ 907 } /* if (fd < 0) */
908 PySys_SetObject("__stdout__", std); 908 PySys_SetObject("__stdout__", std);
909 PySys_SetObject("stdout", std); 909 PySys_SetObject("stdout", std);
910 Py_DECREF(std); 910 Py_DECREF(std);
911 911
912 #if 1 /* Disable this if you have trouble debugging bootstrap stuff */ 912 #if 1 /* Disable this if you have trouble debugging bootstrap stuff */
913 /* Set sys.stderr, replaces the preliminary stderr */ 913 /* Set sys.stderr, replaces the preliminary stderr */
914 fd = fileno(stderr); 914 fd = fileno(stderr);
915 if (fd < 0) { 915 if (fd < 0) {
916 #ifdef MS_WINDOWS 916 #ifdef MS_WINDOWS
917 std = Py_None; 917 std = Py_None;
918 Py_INCREF(std); 918 Py_INCREF(std);
919 #else 919 #else
920 goto error; 920 goto error;
921 #endif 921 #endif
922 } 922 }
923 else { 923 else {
924 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace"); 924 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
925 if (std == NULL) 925 if (std == NULL)
926 goto error; 926 goto error;
927 } /* if (fd < 0) */ 927 } /* if (fd < 0) */
928 928
929 /* Same as hack above, pre-import stderr's codec to avoid recursion 929 /* Same as hack above, pre-import stderr's codec to avoid recursion
930 when import.c tries to write to stderr in verbose mode. */ 930 when import.c tries to write to stderr in verbose mode. */
931 encoding_attr = PyObject_GetAttrString(std, "encoding"); 931 encoding_attr = PyObject_GetAttrString(std, "encoding");
932 if (encoding_attr != NULL) { 932 if (encoding_attr != NULL) {
933 const char * encoding; 933 const char * encoding;
934 encoding = _PyUnicode_AsString(encoding_attr); 934 encoding = _PyUnicode_AsString(encoding_attr);
935 if (encoding != NULL) { 935 if (encoding != NULL) {
936 _PyCodec_Lookup(encoding); 936 _PyCodec_Lookup(encoding);
937 } 937 }
938 } 938 }
939 PyErr_Clear(); /* Not a fatal error if codec isn't available */ 939 PyErr_Clear(); /* Not a fatal error if codec isn't available */
940 940
941 PySys_SetObject("__stderr__", std); 941 PySys_SetObject("__stderr__", std);
942 PySys_SetObject("stderr", std); 942 PySys_SetObject("stderr", std);
943 Py_DECREF(std); 943 Py_DECREF(std);
944 #endif 944 #endif
945 945
946 if (0) { 946 if (0) {
947 error: 947 error:
948 status = -1; 948 status = -1;
949 } 949 }
950 950
951 if (encoding) 951 if (encoding)
952 free(encoding); 952 free(encoding);
953 Py_XDECREF(bimod); 953 Py_XDECREF(bimod);
954 Py_XDECREF(iomod); 954 Py_XDECREF(iomod);
955 return status; 955 return status;
956 } 956 }
957 957
958 /* Parse input from a file and execute it */ 958 /* Parse input from a file and execute it */
959 959
960 int 960 int
961 PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, 961 PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
962 PyCompilerFlags *flags) 962 PyCompilerFlags *flags)
963 { 963 {
964 if (filename == NULL) 964 if (filename == NULL)
965 filename = "???"; 965 filename = "???";
966 if (Py_FdIsInteractive(fp, filename)) { 966 if (Py_FdIsInteractive(fp, filename)) {
967 int err = PyRun_InteractiveLoopFlags(fp, filename, flags); 967 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
968 if (closeit) 968 if (closeit)
969 fclose(fp); 969 fclose(fp);
970 return err; 970 return err;
971 } 971 }
972 else 972 else
973 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags); 973 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
974 } 974 }
975 975
976 int 976 int
977 PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) 977 PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
978 { 978 {
979 PyObject *v; 979 PyObject *v;
980 int ret; 980 int ret;
981 PyCompilerFlags local_flags; 981 PyCompilerFlags local_flags;
982 982
983 if (flags == NULL) { 983 if (flags == NULL) {
984 flags = &local_flags; 984 flags = &local_flags;
985 local_flags.cf_flags = 0; 985 local_flags.cf_flags = 0;
986 } 986 }
987 v = PySys_GetObject("ps1"); 987 v = PySys_GetObject("ps1");
988 if (v == NULL) { 988 if (v == NULL) {
989 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> ")); 989 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
990 Py_XDECREF(v); 990 Py_XDECREF(v);
991 } 991 }
992 v = PySys_GetObject("ps2"); 992 v = PySys_GetObject("ps2");
993 if (v == NULL) { 993 if (v == NULL) {
994 PySys_SetObject("ps2", v = PyUnicode_FromString("... ")); 994 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
995 Py_XDECREF(v); 995 Py_XDECREF(v);
996 } 996 }
997 for (;;) { 997 for (;;) {
998 ret = PyRun_InteractiveOneFlags(fp, filename, flags); 998 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
999 PRINT_TOTAL_REFS(); 999 PRINT_TOTAL_REFS();
1000 if (ret == E_EOF) 1000 if (ret == E_EOF)
1001 return 0; 1001 return 0;
1002 /* 1002 /*
1003 if (ret == E_NOMEM) 1003 if (ret == E_NOMEM)
1004 return -1; 1004 return -1;
1005 */ 1005 */
1006 } 1006 }
1007 } 1007 }
1008 1008
1009 /* compute parser flags based on compiler flags */ 1009 /* compute parser flags based on compiler flags */
1010 static int PARSER_FLAGS(PyCompilerFlags *flags) 1010 static int PARSER_FLAGS(PyCompilerFlags *flags)
1011 { 1011 {
1012 int parser_flags = 0; 1012 int parser_flags = 0;
1013 if (!flags) 1013 if (!flags)
1014 return 0; 1014 return 0;
1015 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) 1015 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1016 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT; 1016 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1017 if (flags->cf_flags & PyCF_IGNORE_COOKIE) 1017 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1018 parser_flags |= PyPARSE_IGNORE_COOKIE; 1018 parser_flags |= PyPARSE_IGNORE_COOKIE;
1019 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) 1019 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1020 parser_flags |= PyPARSE_BARRY_AS_BDFL; 1020 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1021 return parser_flags; 1021 return parser_flags;
1022 } 1022 }
1023 1023
1024 #if 0 1024 #if 0
1025 /* Keep an example of flags with future keyword support. */ 1025 /* Keep an example of flags with future keyword support. */
1026 #define PARSER_FLAGS(flags) \ 1026 #define PARSER_FLAGS(flags) \
1027 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \ 1027 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1028 PyPARSE_DONT_IMPLY_DEDENT : 0) \ 1028 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1029 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \ 1029 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1030 PyPARSE_WITH_IS_KEYWORD : 0)) : 0) 1030 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
1031 #endif 1031 #endif
1032 1032
1033 int 1033 int
1034 PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) 1034 PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
1035 { 1035 {
1036 PyObject *m, *d, *v, *w, *oenc = NULL; 1036 PyObject *m, *d, *v, *w, *oenc = NULL;
1037 mod_ty mod; 1037 mod_ty mod;
1038 PyArena *arena; 1038 PyArena *arena;
1039 char *ps1 = "", *ps2 = "", *enc = NULL; 1039 char *ps1 = "", *ps2 = "", *enc = NULL;
1040 int errcode = 0; 1040 int errcode = 0;
1041 1041
1042 if (fp == stdin) { 1042 if (fp == stdin) {
1043 /* Fetch encoding from sys.stdin */ 1043 /* Fetch encoding from sys.stdin */
1044 v = PySys_GetObject("stdin"); 1044 v = PySys_GetObject("stdin");
1045 if (v == NULL || v == Py_None) 1045 if (v == NULL || v == Py_None)
1046 return -1; 1046 return -1;
1047 oenc = PyObject_GetAttrString(v, "encoding"); 1047 oenc = PyObject_GetAttrString(v, "encoding");
1048 if (!oenc) 1048 if (!oenc)
1049 return -1; 1049 return -1;
1050 enc = _PyUnicode_AsString(oenc); 1050 enc = _PyUnicode_AsString(oenc);
1051 } 1051 }
1052 v = PySys_GetObject("ps1"); 1052 v = PySys_GetObject("ps1");
1053 if (v != NULL) { 1053 if (v != NULL) {
1054 v = PyObject_Str(v); 1054 v = PyObject_Str(v);
1055 if (v == NULL) 1055 if (v == NULL)
1056 PyErr_Clear(); 1056 PyErr_Clear();
1057 else if (PyUnicode_Check(v)) 1057 else if (PyUnicode_Check(v))
1058 ps1 = _PyUnicode_AsString(v); 1058 ps1 = _PyUnicode_AsString(v);
1059 } 1059 }
1060 w = PySys_GetObject("ps2"); 1060 w = PySys_GetObject("ps2");
1061 if (w != NULL) { 1061 if (w != NULL) {
1062 w = PyObject_Str(w); 1062 w = PyObject_Str(w);
1063 if (w == NULL) 1063 if (w == NULL)
1064 PyErr_Clear(); 1064 PyErr_Clear();
1065 else if (PyUnicode_Check(w)) 1065 else if (PyUnicode_Check(w))
1066 ps2 = _PyUnicode_AsString(w); 1066 ps2 = _PyUnicode_AsString(w);
1067 } 1067 }
1068 arena = PyArena_New(); 1068 arena = PyArena_New();
1069 if (arena == NULL) { 1069 if (arena == NULL) {
1070 Py_XDECREF(v); 1070 Py_XDECREF(v);
1071 Py_XDECREF(w); 1071 Py_XDECREF(w);
1072 Py_XDECREF(oenc); 1072 Py_XDECREF(oenc);
1073 return -1; 1073 return -1;
1074 } 1074 }
1075 mod = PyParser_ASTFromFile(fp, filename, enc, 1075 mod = PyParser_ASTFromFile(fp, filename, enc,
1076 Py_single_input, ps1, ps2, 1076 Py_single_input, ps1, ps2,
1077 flags, &errcode, arena); 1077 flags, &errcode, arena);
1078 Py_XDECREF(v); 1078 Py_XDECREF(v);
1079 Py_XDECREF(w); 1079 Py_XDECREF(w);
1080 Py_XDECREF(oenc); 1080 Py_XDECREF(oenc);
1081 if (mod == NULL) { 1081 if (mod == NULL) {
1082 PyArena_Free(arena); 1082 PyArena_Free(arena);
1083 if (errcode == E_EOF) { 1083 if (errcode == E_EOF) {
1084 PyErr_Clear(); 1084 PyErr_Clear();
1085 return E_EOF; 1085 return E_EOF;
1086 } 1086 }
1087 PyErr_Print(); 1087 PyErr_Print();
1088 return -1; 1088 return -1;
1089 } 1089 }
1090 m = PyImport_AddModule("__main__"); 1090 m = PyImport_AddModule("__main__");
1091 if (m == NULL) { 1091 if (m == NULL) {
1092 PyArena_Free(arena); 1092 PyArena_Free(arena);
1093 return -1; 1093 return -1;
1094 } 1094 }
1095 d = PyModule_GetDict(m); 1095 d = PyModule_GetDict(m);
1096 v = run_mod(mod, filename, d, d, flags, arena); 1096 v = run_mod(mod, filename, d, d, flags, arena);
1097 PyArena_Free(arena); 1097 PyArena_Free(arena);
1098 flush_io(); 1098 flush_io();
1099 if (v == NULL) { 1099 if (v == NULL) {
1100 PyErr_Print(); 1100 PyErr_Print();
1101 return -1; 1101 return -1;
1102 } 1102 }
1103 Py_DECREF(v); 1103 Py_DECREF(v);
1104 return 0; 1104 return 0;
1105 } 1105 }
1106 1106
1107 /* Check whether a file maybe a pyc file: Look at the extension, 1107 /* Check whether a file maybe a pyc file: Look at the extension,
1108 the file type, and, if we may close it, at the first few bytes. */ 1108 the file type, and, if we may close it, at the first few bytes. */
1109 1109
1110 static int 1110 static int
1111 maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit) 1111 maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
1112 { 1112 {
1113 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0) 1113 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1114 return 1; 1114 return 1;
1115 1115
1116 /* Only look into the file if we are allowed to close it, since 1116 /* Only look into the file if we are allowed to close it, since
1117 it then should also be seekable. */ 1117 it then should also be seekable. */
1118 if (closeit) { 1118 if (closeit) {
1119 /* Read only two bytes of the magic. If the file was opened in 1119 /* Read only two bytes of the magic. If the file was opened in
1120 text mode, the bytes 3 and 4 of the magic (\r\n) might not 1120 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1121 be read as they are on disk. */ 1121 be read as they are on disk. */
1122 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF; 1122 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1123 unsigned char buf[2]; 1123 unsigned char buf[2];
1124 /* Mess: In case of -x, the stream is NOT at its start now, 1124 /* Mess: In case of -x, the stream is NOT at its start now,
1125 and ungetc() was used to push back the first newline, 1125 and ungetc() was used to push back the first newline,
1126 which makes the current stream position formally undefined, 1126 which makes the current stream position formally undefined,
1127 and a x-platform nightmare. 1127 and a x-platform nightmare.
1128 Unfortunately, we have no direct way to know whether -x 1128 Unfortunately, we have no direct way to know whether -x
1129 was specified. So we use a terrible hack: if the current 1129 was specified. So we use a terrible hack: if the current
1130 stream position is not 0, we assume -x was specified, and 1130 stream position is not 0, we assume -x was specified, and
1131 give up. Bug 132850 on SourceForge spells out the 1131 give up. Bug 132850 on SourceForge spells out the
1132 hopelessness of trying anything else (fseek and ftell 1132 hopelessness of trying anything else (fseek and ftell
1133 don't work predictably x-platform for text-mode files). 1133 don't work predictably x-platform for text-mode files).
1134 */ 1134 */
1135 int ispyc = 0; 1135 int ispyc = 0;
1136 if (ftell(fp) == 0) { 1136 if (ftell(fp) == 0) {
1137 if (fread(buf, 1, 2, fp) == 2 && 1137 if (fread(buf, 1, 2, fp) == 2 &&
1138 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic) 1138 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1139 ispyc = 1; 1139 ispyc = 1;
1140 rewind(fp); 1140 rewind(fp);
1141 } 1141 }
1142 return ispyc; 1142 return ispyc;
1143 } 1143 }
1144 return 0; 1144 return 0;
1145 } 1145 }
1146 1146
1147 int 1147 int
1148 PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, 1148 PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
1149 PyCompilerFlags *flags) 1149 PyCompilerFlags *flags)
1150 { 1150 {
1151 PyObject *m, *d, *v; 1151 PyObject *m, *d, *v;
1152 const char *ext; 1152 const char *ext;
1153 int set_file_name = 0, ret, len; 1153 int set_file_name = 0, ret, len;
1154 1154
1155 m = PyImport_AddModule("__main__"); 1155 m = PyImport_AddModule("__main__");
1156 if (m == NULL) 1156 if (m == NULL)
1157 return -1; 1157 return -1;
1158 d = PyModule_GetDict(m); 1158 d = PyModule_GetDict(m);
1159 if (PyDict_GetItemString(d, "__file__") == NULL) { 1159 if (PyDict_GetItemString(d, "__file__") == NULL) {
1160 PyObject *f; 1160 PyObject *f;
1161 f = PyUnicode_DecodeFSDefault(filename); 1161 f = PyUnicode_DecodeFSDefault(filename);
1162 if (f == NULL) 1162 if (f == NULL)
1163 return -1; 1163 return -1;
1164 if (PyDict_SetItemString(d, "__file__", f) < 0) { 1164 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1165 Py_DECREF(f); 1165 Py_DECREF(f);
1166 return -1; 1166 return -1;
1167 } 1167 }
1168 set_file_name = 1; 1168 set_file_name = 1;
1169 Py_DECREF(f); 1169 Py_DECREF(f);
1170 } 1170 }
1171 len = strlen(filename); 1171 len = strlen(filename);
1172 ext = filename + len - (len > 4 ? 4 : 0); 1172 ext = filename + len - (len > 4 ? 4 : 0);
1173 if (maybe_pyc_file(fp, filename, ext, closeit)) { 1173 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1174 /* Try to run a pyc file. First, re-open in binary */ 1174 /* Try to run a pyc file. First, re-open in binary */
1175 if (closeit) 1175 if (closeit)
1176 fclose(fp); 1176 fclose(fp);
1177 if ((fp = fopen(filename, "rb")) == NULL) { 1177 if ((fp = fopen(filename, "rb")) == NULL) {
1178 fprintf(stderr, "python: Can't reopen .pyc file\n"); 1178 fprintf(stderr, "python: Can't reopen .pyc file\n");
1179 ret = -1; 1179 ret = -1;
1180 goto done; 1180 goto done;
1181 } 1181 }
1182 /* Turn on optimization if a .pyo file is given */ 1182 /* Turn on optimization if a .pyo file is given */
1183 if (strcmp(ext, ".pyo") == 0) 1183 if (strcmp(ext, ".pyo") == 0)
1184 Py_OptimizeFlag = 1; 1184 Py_OptimizeFlag = 1;
1185 v = run_pyc_file(fp, filename, d, d, flags); 1185 v = run_pyc_file(fp, filename, d, d, flags);
1186 } else { 1186 } else {
1187 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, 1187 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1188 closeit, flags); 1188 closeit, flags);
1189 } 1189 }
1190 flush_io(); 1190 flush_io();
1191 if (v == NULL) { 1191 if (v == NULL) {
1192 PyErr_Print(); 1192 PyErr_Print();
1193 ret = -1; 1193 ret = -1;
1194 goto done; 1194 goto done;
1195 } 1195 }
1196 Py_DECREF(v); 1196 Py_DECREF(v);
1197 ret = 0; 1197 ret = 0;
1198 done: 1198 done:
1199 if (set_file_name && PyDict_DelItemString(d, "__file__")) 1199 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1200 PyErr_Clear(); 1200 PyErr_Clear();
1201 return ret; 1201 return ret;
1202 } 1202 }
1203 1203
1204 int 1204 int
1205 PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) 1205 PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
1206 { 1206 {
1207 PyObject *m, *d, *v; 1207 PyObject *m, *d, *v;
1208 m = PyImport_AddModule("__main__"); 1208 m = PyImport_AddModule("__main__");
1209 if (m == NULL) 1209 if (m == NULL)
1210 return -1; 1210 return -1;
1211 d = PyModule_GetDict(m); 1211 d = PyModule_GetDict(m);
1212 v = PyRun_StringFlags(command, Py_file_input, d, d, flags); 1212 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1213 if (v == NULL) { 1213 if (v == NULL) {
1214 PyErr_Print(); 1214 PyErr_Print();
1215 return -1; 1215 return -1;
1216 } 1216 }
1217 Py_DECREF(v); 1217 Py_DECREF(v);
1218 return 0; 1218 return 0;
1219 } 1219 }
1220 1220
1221 static int 1221 static int
1222 parse_syntax_error(PyObject *err, PyObject **message, const char **filename, 1222 parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1223 int *lineno, int *offset, const char **text) 1223 int *lineno, int *offset, const char **text)
1224 { 1224 {
1225 long hold; 1225 long hold;
1226 PyObject *v; 1226 PyObject *v;
1227 1227
1228 /* old style errors */ 1228 /* old style errors */
1229 if (PyTuple_Check(err)) 1229 if (PyTuple_Check(err))
1230 return PyArg_ParseTuple(err, "O(ziiz)", message, filename, 1230 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1231 lineno, offset, text); 1231 lineno, offset, text);
1232 1232
1233 /* new style errors. `err' is an instance */ 1233 /* new style errors. `err' is an instance */
1234 1234
1235 if (! (v = PyObject_GetAttrString(err, "msg"))) 1235 if (! (v = PyObject_GetAttrString(err, "msg")))
1236 goto finally; 1236 goto finally;
1237 *message = v; 1237 *message = v;
1238 1238
1239 if (!(v = PyObject_GetAttrString(err, "filename"))) 1239 if (!(v = PyObject_GetAttrString(err, "filename")))
1240 goto finally; 1240 goto finally;
1241 if (v == Py_None) 1241 if (v == Py_None)
1242 *filename = NULL; 1242 *filename = NULL;
1243 else if (! (*filename = _PyUnicode_AsString(v))) 1243 else if (! (*filename = _PyUnicode_AsString(v)))
1244 goto finally; 1244 goto finally;
1245 1245
1246 Py_DECREF(v); 1246 Py_DECREF(v);
1247 if (!(v = PyObject_GetAttrString(err, "lineno"))) 1247 if (!(v = PyObject_GetAttrString(err, "lineno")))
1248 goto finally; 1248 goto finally;
1249 hold = PyLong_AsLong(v); 1249 hold = PyLong_AsLong(v);
1250 Py_DECREF(v); 1250 Py_DECREF(v);
1251 v = NULL; 1251 v = NULL;
1252 if (hold < 0 && PyErr_Occurred()) 1252 if (hold < 0 && PyErr_Occurred())
1253 goto finally; 1253 goto finally;
1254 *lineno = (int)hold; 1254 *lineno = (int)hold;
1255 1255
1256 if (!(v = PyObject_GetAttrString(err, "offset"))) 1256 if (!(v = PyObject_GetAttrString(err, "offset")))
1257 goto finally; 1257 goto finally;
1258 if (v == Py_None) { 1258 if (v == Py_None) {
1259 *offset = -1; 1259 *offset = -1;
1260 Py_DECREF(v); 1260 Py_DECREF(v);
1261 v = NULL; 1261 v = NULL;
1262 } else { 1262 } else {
1263 hold = PyLong_AsLong(v); 1263 hold = PyLong_AsLong(v);
1264 Py_DECREF(v); 1264 Py_DECREF(v);
1265 v = NULL; 1265 v = NULL;
1266 if (hold < 0 && PyErr_Occurred()) 1266 if (hold < 0 && PyErr_Occurred())
1267 goto finally; 1267 goto finally;
1268 *offset = (int)hold; 1268 *offset = (int)hold;
1269 } 1269 }
1270 1270
1271 if (!(v = PyObject_GetAttrString(err, "text"))) 1271 if (!(v = PyObject_GetAttrString(err, "text")))
1272 goto finally; 1272 goto finally;
1273 if (v == Py_None) 1273 if (v == Py_None)
1274 *text = NULL; 1274 *text = NULL;
1275 else if (!PyUnicode_Check(v) || 1275 else if (!PyUnicode_Check(v) ||
1276 !(*text = _PyUnicode_AsString(v))) 1276 !(*text = _PyUnicode_AsString(v)))
1277 goto finally; 1277 goto finally;
1278 Py_DECREF(v); 1278 Py_DECREF(v);
1279 return 1; 1279 return 1;
1280 1280
1281 finally: 1281 finally:
1282 Py_XDECREF(v); 1282 Py_XDECREF(v);
1283 return 0; 1283 return 0;
1284 } 1284 }
1285 1285
1286 void 1286 void
1287 PyErr_Print(void) 1287 PyErr_Print(void)
1288 { 1288 {
1289 PyErr_PrintEx(1); 1289 PyErr_PrintEx(1);
1290 } 1290 }
1291 1291
1292 static void 1292 static void
1293 print_error_text(PyObject *f, int offset, const char *text) 1293 print_error_text(PyObject *f, int offset, const char *text)
1294 { 1294 {
1295 char *nl; 1295 char *nl;
1296 if (offset >= 0) { 1296 if (offset >= 0) {
1297 if (offset > 0 && offset == (int)strlen(text)) 1297 if (offset > 0 && offset == (int)strlen(text))
1298 offset--; 1298 offset--;
1299 for (;;) { 1299 for (;;) {
1300 nl = strchr(text, '\n'); 1300 nl = strchr(text, '\n');
1301 if (nl == NULL || nl-text >= offset) 1301 if (nl == NULL || nl-text >= offset)
1302 break; 1302 break;
1303 offset -= (int)(nl+1-text); 1303 offset -= (int)(nl+1-text);
1304 text = nl+1; 1304 text = nl+1;
1305 } 1305 }
1306 while (*text == ' ' || *text == '\t') { 1306 while (*text == ' ' || *text == '\t') {
1307 text++; 1307 text++;
1308 offset--; 1308 offset--;
1309 } 1309 }
1310 } 1310 }
1311 PyFile_WriteString(" ", f); 1311 PyFile_WriteString(" ", f);
1312 PyFile_WriteString(text, f); 1312 PyFile_WriteString(text, f);
1313 if (*text == '\0' || text[strlen(text)-1] != '\n') 1313 if (*text == '\0' || text[strlen(text)-1] != '\n')
1314 PyFile_WriteString("\n", f); 1314 PyFile_WriteString("\n", f);
1315 if (offset == -1) 1315 if (offset == -1)
1316 return; 1316 return;
1317 PyFile_WriteString(" ", f); 1317 PyFile_WriteString(" ", f);
1318 offset--; 1318 offset--;
1319 while (offset > 0) { 1319 while (offset > 0) {
1320 PyFile_WriteString(" ", f); 1320 PyFile_WriteString(" ", f);
1321 offset--; 1321 offset--;
1322 } 1322 }
1323 PyFile_WriteString("^\n", f); 1323 PyFile_WriteString("^\n", f);
1324 } 1324 }
1325 1325
1326 static void 1326 static void
1327 handle_system_exit(void) 1327 handle_system_exit(void)
1328 { 1328 {
1329 PyObject *exception, *value, *tb; 1329 PyObject *exception, *value, *tb;
1330 int exitcode = 0; 1330 int exitcode = 0;
1331 1331
1332 if (Py_InspectFlag) 1332 if (Py_InspectFlag)
1333 /* Don't exit if -i flag was given. This flag is set to 0 1333 /* Don't exit if -i flag was given. This flag is set to 0
1334 * when entering interactive mode for inspecting. */ 1334 * when entering interactive mode for inspecting. */
1335 return; 1335 return;
1336 1336
1337 PyErr_Fetch(&exception, &value, &tb); 1337 PyErr_Fetch(&exception, &value, &tb);
1338 fflush(stdout); 1338 fflush(stdout);
1339 if (value == NULL || value == Py_None) 1339 if (value == NULL || value == Py_None)
1340 goto done; 1340 goto done;
1341 if (PyExceptionInstance_Check(value)) { 1341 if (PyExceptionInstance_Check(value)) {
1342 /* The error code should be in the `code' attribute. */ 1342 /* The error code should be in the `code' attribute. */
1343 PyObject *code = PyObject_GetAttrString(value, "code"); 1343 PyObject *code = PyObject_GetAttrString(value, "code");
1344 if (code) { 1344 if (code) {
1345 Py_DECREF(value); 1345 Py_DECREF(value);
1346 value = code; 1346 value = code;
1347 if (value == Py_None) 1347 if (value == Py_None)
1348 goto done; 1348 goto done;
1349 } 1349 }
1350 /* If we failed to dig out the 'code' attribute, 1350 /* If we failed to dig out the 'code' attribute,
1351 just let the else clause below print the error. */ 1351 just let the else clause below print the error. */
1352 } 1352 }
1353 if (PyLong_Check(value)) 1353 if (PyLong_Check(value))
1354 exitcode = (int)PyLong_AsLong(value); 1354 exitcode = (int)PyLong_AsLong(value);
1355 else { 1355 else {
1356 PyObject_Print(value, stderr, Py_PRINT_RAW); 1356 PyObject_Print(value, stderr, Py_PRINT_RAW);
1357 PySys_WriteStderr("\n"); 1357 PySys_WriteStderr("\n");
1358 exitcode = 1; 1358 exitcode = 1;
1359 } 1359 }
1360 done: 1360 done:
1361 /* Restore and clear the exception info, in order to properly decref 1361 /* Restore and clear the exception info, in order to properly decref
1362 * the exception, value, and traceback. If we just exit instead, 1362 * the exception, value, and traceback. If we just exit instead,
1363 * these leak, which confuses PYTHONDUMPREFS output, and may prevent 1363 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1364 * some finalizers from running. 1364 * some finalizers from running.
1365 */ 1365 */
1366 PyErr_Restore(exception, value, tb); 1366 PyErr_Restore(exception, value, tb);
1367 PyErr_Clear(); 1367 PyErr_Clear();
1368 Py_Exit(exitcode); 1368 Py_Exit(exitcode);
1369 /* NOTREACHED */ 1369 /* NOTREACHED */
1370 } 1370 }
1371 1371
1372 void 1372 void
1373 PyErr_PrintEx(int set_sys_last_vars) 1373 PyErr_PrintEx(int set_sys_last_vars)
1374 { 1374 {
1375 PyObject *exception, *v, *tb, *hook; 1375 PyObject *exception, *v, *tb, *hook;
1376 1376
1377 if (PyErr_ExceptionMatches(PyExc_SystemExit)) { 1377 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1378 handle_system_exit(); 1378 handle_system_exit();
1379 } 1379 }
1380 PyErr_Fetch(&exception, &v, &tb); 1380 PyErr_Fetch(&exception, &v, &tb);
1381 if (exception == NULL) 1381 if (exception == NULL)
1382 return; 1382 return;
1383 PyErr_NormalizeException(&exception, &v, &tb); 1383 PyErr_NormalizeException(&exception, &v, &tb);
1384 if (tb == NULL) { 1384 if (tb == NULL) {
1385 tb = Py_None; 1385 tb = Py_None;
1386 Py_INCREF(tb); 1386 Py_INCREF(tb);
1387 } 1387 }
1388 PyException_SetTraceback(v, tb); 1388 PyException_SetTraceback(v, tb);
1389 if (exception == NULL) 1389 if (exception == NULL)
1390 return; 1390 return;
1391 /* Now we know v != NULL too */ 1391 /* Now we know v != NULL too */
1392 if (set_sys_last_vars) { 1392 if (set_sys_last_vars) {
1393 PySys_SetObject("last_type", exception); 1393 PySys_SetObject("last_type", exception);
1394 PySys_SetObject("last_value", v); 1394 PySys_SetObject("last_value", v);
1395 PySys_SetObject("last_traceback", tb); 1395 PySys_SetObject("last_traceback", tb);
1396 } 1396 }
1397 hook = PySys_GetObject("excepthook"); 1397 hook = PySys_GetObject("excepthook");
1398 if (hook) { 1398 if (hook) {
1399 PyObject *args = PyTuple_Pack(3, exception, v, tb); 1399 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1400 PyObject *result = PyEval_CallObject(hook, args); 1400 PyObject *result = PyEval_CallObject(hook, args);
1401 if (result == NULL) { 1401 if (result == NULL) {
1402 PyObject *exception2, *v2, *tb2; 1402 PyObject *exception2, *v2, *tb2;
1403 if (PyErr_ExceptionMatches(PyExc_SystemExit)) { 1403 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1404 handle_system_exit(); 1404 handle_system_exit();
1405 } 1405 }
1406 PyErr_Fetch(&exception2, &v2, &tb2); 1406 PyErr_Fetch(&exception2, &v2, &tb2);
1407 PyErr_NormalizeException(&exception2, &v2, &tb2); 1407 PyErr_NormalizeException(&exception2, &v2, &tb2);
1408 /* It should not be possible for exception2 or v2 1408 /* It should not be possible for exception2 or v2
1409 to be NULL. However PyErr_Display() can't 1409 to be NULL. However PyErr_Display() can't
1410 tolerate NULLs, so just be safe. */ 1410 tolerate NULLs, so just be safe. */
1411 if (exception2 == NULL) { 1411 if (exception2 == NULL) {
1412 exception2 = Py_None; 1412 exception2 = Py_None;
1413 Py_INCREF(exception2); 1413 Py_INCREF(exception2);
1414 } 1414 }
1415 if (v2 == NULL) { 1415 if (v2 == NULL) {
1416 v2 = Py_None; 1416 v2 = Py_None;
1417 Py_INCREF(v2); 1417 Py_INCREF(v2);
1418 } 1418 }
1419 fflush(stdout); 1419 fflush(stdout);
1420 PySys_WriteStderr("Error in sys.excepthook:\n"); 1420 PySys_WriteStderr("Error in sys.excepthook:\n");
1421 PyErr_Display(exception2, v2, tb2); 1421 PyErr_Display(exception2, v2, tb2);
1422 PySys_WriteStderr("\nOriginal exception was:\n"); 1422 PySys_WriteStderr("\nOriginal exception was:\n");
1423 PyErr_Display(exception, v, tb); 1423 PyErr_Display(exception, v, tb);
1424 Py_DECREF(exception2); 1424 Py_DECREF(exception2);
1425 Py_DECREF(v2); 1425 Py_DECREF(v2);
1426 Py_XDECREF(tb2); 1426 Py_XDECREF(tb2);
1427 } 1427 }
1428 Py_XDECREF(result); 1428 Py_XDECREF(result);
1429 Py_XDECREF(args); 1429 Py_XDECREF(args);
1430 } else { 1430 } else {
1431 PySys_WriteStderr("sys.excepthook is missing\n"); 1431 PySys_WriteStderr("sys.excepthook is missing\n");
1432 PyErr_Display(exception, v, tb); 1432 PyErr_Display(exception, v, tb);
1433 } 1433 }
1434 Py_XDECREF(exception); 1434 Py_XDECREF(exception);
1435 Py_XDECREF(v); 1435 Py_XDECREF(v);
1436 Py_XDECREF(tb); 1436 Py_XDECREF(tb);
1437 } 1437 }
1438 1438
1439 static void 1439 static void
1440 print_exception(PyObject *f, PyObject *value) 1440 print_exception(PyObject *f, PyObject *value)
1441 { 1441 {
1442 int err = 0; 1442 int err = 0;
1443 PyObject *type, *tb; 1443 PyObject *type, *tb;
1444 1444
1445 if (!PyExceptionInstance_Check(value)) { 1445 if (!PyExceptionInstance_Check(value)) {
1446 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); 1446 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1447 PyFile_WriteString(Py_TYPE(value)->tp_name, f); 1447 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1448 PyFile_WriteString(" found\n", f); 1448 PyFile_WriteString(" found\n", f);
1449 return; 1449 return;
1450 } 1450 }
1451 1451
1452 Py_INCREF(value); 1452 Py_INCREF(value);
1453 fflush(stdout); 1453 fflush(stdout);
1454 type = (PyObject *) Py_TYPE(value); 1454 type = (PyObject *) Py_TYPE(value);
1455 tb = PyException_GetTraceback(value); 1455 tb = PyException_GetTraceback(value);
1456 if (tb && tb != Py_None) 1456 if (tb && tb != Py_None)
1457 err = PyTraceBack_Print(tb, f); 1457 err = PyTraceBack_Print(tb, f);
1458 if (err == 0 && 1458 if (err == 0 &&
1459 PyObject_HasAttrString(value, "print_file_and_line")) 1459 PyObject_HasAttrString(value, "print_file_and_line"))
1460 { 1460 {
1461 PyObject *message; 1461 PyObject *message;
1462 const char *filename, *text; 1462 const char *filename, *text;
1463 int lineno, offset; 1463 int lineno, offset;
1464 if (!parse_syntax_error(value, &message, &filename, 1464 if (!parse_syntax_error(value, &message, &filename,
1465 &lineno, &offset, &text)) 1465 &lineno, &offset, &text))
1466 PyErr_Clear(); 1466 PyErr_Clear();
1467 else { 1467 else {
1468 char buf[10]; 1468 char buf[10];
1469 PyFile_WriteString(" File \"", f); 1469 PyFile_WriteString(" File \"", f);
1470 if (filename == NULL) 1470 if (filename == NULL)
1471 PyFile_WriteString("<string>", f); 1471 PyFile_WriteString("<string>", f);
1472 else 1472 else
1473 PyFile_WriteString(filename, f); 1473 PyFile_WriteString(filename, f);
1474 PyFile_WriteString("\", line ", f); 1474 PyFile_WriteString("\", line ", f);
1475 PyOS_snprintf(buf, sizeof(buf), "%d", lineno); 1475 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1476 PyFile_WriteString(buf, f); 1476 PyFile_WriteString(buf, f);
1477 PyFile_WriteString("\n", f); 1477 PyFile_WriteString("\n", f);
1478 if (text != NULL) 1478 if (text != NULL)
1479 print_error_text(f, offset, text); 1479 print_error_text(f, offset, text);
1480 Py_DECREF(value); 1480 Py_DECREF(value);
1481 value = message; 1481 value = message;
1482 /* Can't be bothered to check all those 1482 /* Can't be bothered to check all those
1483 PyFile_WriteString() calls */ 1483 PyFile_WriteString() calls */
1484 if (PyErr_Occurred()) 1484 if (PyErr_Occurred())
1485 err = -1; 1485 err = -1;
1486 } 1486 }
1487 } 1487 }
1488 if (err) { 1488 if (err) {
1489 /* Don't do anything else */ 1489 /* Don't do anything else */
1490 } 1490 }
1491 else { 1491 else {
1492 PyObject* moduleName; 1492 PyObject* moduleName;
1493 char* className; 1493 char* className;
1494 assert(PyExceptionClass_Check(type)); 1494 assert(PyExceptionClass_Check(type));
1495 className = PyExceptionClass_Name(type); 1495 className = PyExceptionClass_Name(type);
1496 if (className != NULL) { 1496 if (className != NULL) {
1497 char *dot = strrchr(className, '.'); 1497 char *dot = strrchr(className, '.');
1498 if (dot != NULL) 1498 if (dot != NULL)
1499 className = dot+1; 1499 className = dot+1;
1500 } 1500 }
1501 1501
1502 moduleName = PyObject_GetAttrString(type, "__module__"); 1502 moduleName = PyObject_GetAttrString(type, "__module__");
1503 if (moduleName == NULL || !PyUnicode_Check(moduleName)) 1503 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1504 { 1504 {
1505 Py_DECREF(moduleName); 1505 Py_DECREF(moduleName);
1506 err = PyFile_WriteString("<unknown>", f); 1506 err = PyFile_WriteString("<unknown>", f);
1507 } 1507 }
1508 else { 1508 else {
1509 char* modstr = _PyUnicode_AsString(moduleName); 1509 char* modstr = _PyUnicode_AsString(moduleName);
1510 if (modstr && strcmp(modstr, "builtins")) 1510 if (modstr && strcmp(modstr, "builtins"))
1511 { 1511 {
1512 err = PyFile_WriteString(modstr, f); 1512 err = PyFile_WriteString(modstr, f);
1513 err += PyFile_WriteString(".", f); 1513 err += PyFile_WriteString(".", f);
1514 } 1514 }
1515 Py_DECREF(moduleName); 1515 Py_DECREF(moduleName);
1516 } 1516 }
1517 if (err == 0) { 1517 if (err == 0) {
1518 if (className == NULL) 1518 if (className == NULL)
1519 err = PyFile_WriteString("<unknown>", f); 1519 err = PyFile_WriteString("<unknown>", f);
1520 else 1520 else
1521 err = PyFile_WriteString(className, f); 1521 err = PyFile_WriteString(className, f);
1522 } 1522 }
1523 } 1523 }
1524 if (err == 0 && (value != Py_None)) { 1524 if (err == 0 && (value != Py_None)) {
1525 PyObject *s = PyObject_Str(value); 1525 PyObject *s = PyObject_Str(value);
1526 /* only print colon if the str() of the 1526 /* only print colon if the str() of the
1527 object is not the empty string 1527 object is not the empty string
1528 */ 1528 */
1529 if (s == NULL) 1529 if (s == NULL)
1530 err = -1; 1530 err = -1;
1531 else if (!PyUnicode_Check(s) || 1531 else if (!PyUnicode_Check(s) ||
1532 PyUnicode_GetSize(s) != 0) 1532 PyUnicode_GetSize(s) != 0)
1533 err = PyFile_WriteString(": ", f); 1533 err = PyFile_WriteString(": ", f);
1534 if (err == 0) 1534 if (err == 0)
1535 err = PyFile_WriteObject(s, f, Py_PRINT_RAW); 1535 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1536 Py_XDECREF(s); 1536 Py_XDECREF(s);
1537 } 1537 }
1538 /* try to write a newline in any case */ 1538 /* try to write a newline in any case */
1539 err += PyFile_WriteString("\n", f); 1539 err += PyFile_WriteString("\n", f);
1540 Py_XDECREF(tb); 1540 Py_XDECREF(tb);
1541 Py_DECREF(value); 1541 Py_DECREF(value);
1542 /* If an error happened here, don't show it. 1542 /* If an error happened here, don't show it.
1543 XXX This is wrong, but too many callers rely on this behavior. */ 1543 XXX This is wrong, but too many callers rely on this behavior. */
1544 if (err != 0) 1544 if (err != 0)
1545 PyErr_Clear(); 1545 PyErr_Clear();
1546 } 1546 }
1547 1547
1548 static const char *cause_message = 1548 static const char *cause_message =
1549 "\nThe above exception was the direct cause " 1549 "\nThe above exception was the direct cause "
1550 "of the following exception:\n\n"; 1550 "of the following exception:\n\n";
1551 1551
1552 static const char *context_message = 1552 static const char *context_message =
1553 "\nDuring handling of the above exception, " 1553 "\nDuring handling of the above exception, "
1554 "another exception occurred:\n\n"; 1554 "another exception occurred:\n\n";
1555 1555
1556 static void 1556 static void
1557 print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen) 1557 print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1558 { 1558 {
1559 int err = 0, res; 1559 int err = 0, res;
1560 PyObject *cause, *context; 1560 PyObject *cause, *context;
1561 1561
1562 if (seen != NULL) { 1562 if (seen != NULL) {
1563 /* Exception chaining */ 1563 /* Exception chaining */
1564 if (PySet_Add(seen, value) == -1) 1564 if (PySet_Add(seen, value) == -1)
1565 PyErr_Clear(); 1565 PyErr_Clear();
1566 else if (PyExceptionInstance_Check(value)) { 1566 else if (PyExceptionInstance_Check(value)) {
1567 cause = PyException_GetCause(value); 1567 cause = PyException_GetCause(value);
1568 context = PyException_GetContext(value); 1568 context = PyException_GetContext(value);
1569 if (cause) { 1569 if (cause) {
1570 res = PySet_Contains(seen, cause); 1570 res = PySet_Contains(seen, cause);
1571 if (res == -1) 1571 if (res == -1)
1572 PyErr_Clear(); 1572 PyErr_Clear();
1573 if (res == 0) { 1573 if (res == 0) {
1574 print_exception_recursive( 1574 print_exception_recursive(
1575 f, cause, seen); 1575 f, cause, seen);
1576 err |= PyFile_WriteString( 1576 err |= PyFile_WriteString(
1577 cause_message, f); 1577 cause_message, f);
1578 } 1578 }
1579 } 1579 }
1580 else if (context) { 1580 else if (context) {
1581 res = PySet_Contains(seen, context); 1581 res = PySet_Contains(seen, context);
1582 if (res == -1) 1582 if (res == -1)
1583 PyErr_Clear(); 1583 PyErr_Clear();
1584 if (res == 0) { 1584 if (res == 0) {
1585 print_exception_recursive( 1585 print_exception_recursive(
1586 f, context, seen); 1586 f, context, seen);
1587 err |= PyFile_WriteString( 1587 err |= PyFile_WriteString(
1588 context_message, f); 1588 context_message, f);
1589 } 1589 }
1590 } 1590 }
1591 Py_XDECREF(context); 1591 Py_XDECREF(context);
1592 Py_XDECREF(cause); 1592 Py_XDECREF(cause);
1593 } 1593 }
1594 } 1594 }
1595 print_exception(f, value); 1595 print_exception(f, value);
1596 if (err != 0) 1596 if (err != 0)
1597 PyErr_Clear(); 1597 PyErr_Clear();
1598 } 1598 }
1599 1599
1600 void 1600 void
1601 PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) 1601 PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1602 { 1602 {
1603 PyObject *seen; 1603 PyObject *seen;
1604 PyObject *f = PySys_GetObject("stderr"); 1604 PyObject *f = PySys_GetObject("stderr");
1605 if (f == Py_None) { 1605 if (f == Py_None) {
1606 /* pass */ 1606 /* pass */
1607 } 1607 }
1608 else if (f == NULL) { 1608 else if (f == NULL) {
1609 _PyObject_Dump(value); 1609 _PyObject_Dump(value);
1610 fprintf(stderr, "lost sys.stderr\n"); 1610 fprintf(stderr, "lost sys.stderr\n");
1611 } 1611 }
1612 else { 1612 else {
1613 /* We choose to ignore seen being possibly NULL, and report 1613 /* We choose to ignore seen being possibly NULL, and report
1614 at least the main exception (it could be a MemoryError). 1614 at least the main exception (it could be a MemoryError).
1615 */ 1615 */
1616 seen = PySet_New(NULL); 1616 seen = PySet_New(NULL);
1617 if (seen == NULL) 1617 if (seen == NULL)
1618 PyErr_Clear(); 1618 PyErr_Clear();
1619 print_exception_recursive(f, value, seen); 1619 print_exception_recursive(f, value, seen);
1620 Py_XDECREF(seen); 1620 Py_XDECREF(seen);
1621 } 1621 }
1622 } 1622 }
1623 1623
1624 PyObject * 1624 PyObject *
1625 PyRun_StringFlags(const char *str, int start, PyObject *globals, 1625 PyRun_StringFlags(const char *str, int start, PyObject *globals,
1626 PyObject *locals, PyCompilerFlags *flags) 1626 PyObject *locals, PyCompilerFlags *flags)
1627 { 1627 {
1628 PyObject *ret = NULL; 1628 PyObject *ret = NULL;
1629 mod_ty mod; 1629 mod_ty mod;
1630 PyArena *arena = PyArena_New(); 1630 PyArena *arena = PyArena_New();
1631 if (arena == NULL) 1631 if (arena == NULL)
1632 return NULL; 1632 return NULL;
1633 1633
1634 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena); 1634 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1635 if (mod != NULL) 1635 if (mod != NULL)
1636 ret = run_mod(mod, "<string>", globals, locals, flags, arena); 1636 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1637 PyArena_Free(arena); 1637 PyArena_Free(arena);
1638 return ret; 1638 return ret;
1639 } 1639 }
1640 1640
1641 PyObject * 1641 PyObject *
1642 PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, 1642 PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1643 PyObject *locals, int closeit, PyCompilerFlags *flags) 1643 PyObject *locals, int closeit, PyCompilerFlags *flags)
1644 { 1644 {
1645 PyObject *ret; 1645 PyObject *ret;
1646 mod_ty mod; 1646 mod_ty mod;
1647 PyArena *arena = PyArena_New(); 1647 PyArena *arena = PyArena_New();
1648 if (arena == NULL) 1648 if (arena == NULL)
1649 return NULL; 1649 return NULL;
1650 1650
1651 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0, 1651 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1652 flags, NULL, arena); 1652 flags, NULL, arena);
1653 if (closeit) 1653 if (closeit)
1654 fclose(fp); 1654 fclose(fp);
1655 if (mod == NULL) { 1655 if (mod == NULL) {
1656 PyArena_Free(arena); 1656 PyArena_Free(arena);
1657 return NULL; 1657 return NULL;
1658 } 1658 }
1659 ret = run_mod(mod, filename, globals, locals, flags, arena); 1659 ret = run_mod(mod, filename, globals, locals, flags, arena);
1660 PyArena_Free(arena); 1660 PyArena_Free(arena);
1661 return ret; 1661 return ret;
1662 } 1662 }
1663 1663
1664 static void 1664 static void
1665 flush_io(void) 1665 flush_io(void)
1666 { 1666 {
1667 PyObject *f, *r; 1667 PyObject *f, *r;
1668 PyObject *type, *value, *traceback; 1668 PyObject *type, *value, *traceback;
1669 1669
1670 /* Save the current exception */ 1670 /* Save the current exception */
1671 PyErr_Fetch(&type, &value, &traceback); 1671 PyErr_Fetch(&type, &value, &traceback);
1672 1672
1673 f = PySys_GetObject("stderr"); 1673 f = PySys_GetObject("stderr");
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 f = PySys_GetObject("stdout"); 1681 f = PySys_GetObject("stdout");
1682 if (f != NULL) { 1682 if (f != NULL) {
1683 r = PyObject_CallMethod(f, "flush", ""); 1683 r = PyObject_CallMethod(f, "flush", "");
1684 if (r) 1684 if (r)
1685 Py_DECREF(r); 1685 Py_DECREF(r);
1686 else 1686 else
1687 PyErr_Clear(); 1687 PyErr_Clear();
1688 } 1688 }
1689 1689
1690 PyErr_Restore(type, value, traceback); 1690 PyErr_Restore(type, value, traceback);
1691 } 1691 }
1692 1692
1693 static PyObject * 1693 static PyObject *
1694 run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals, 1694 run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
1695 PyCompilerFlags *flags, PyArena *arena) 1695 PyCompilerFlags *flags, PyArena *arena)
1696 { 1696 {
1697 PyCodeObject *co; 1697 PyCodeObject *co;
1698 PyObject *v; 1698 PyObject *v;
1699 co = PyAST_Compile(mod, filename, flags, arena); 1699 co = PyAST_Compile(mod, filename, flags, arena);
1700 if (co == NULL) 1700 if (co == NULL)
1701 return NULL; 1701 return NULL;
1702 v = PyEval_EvalCode(co, globals, locals); 1702 v = PyEval_EvalCode(co, globals, locals);
1703 Py_DECREF(co); 1703 Py_DECREF(co);
1704 return v; 1704 return v;
1705 } 1705 }
1706 1706
1707 static PyObject * 1707 static PyObject *
1708 run_pyc_file(FILE *fp, const char *filename, PyObject *globals, 1708 run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
1709 PyObject *locals, PyCompilerFlags *flags) 1709 PyObject *locals, PyCompilerFlags *flags)
1710 { 1710 {
1711 PyCodeObject *co; 1711 PyCodeObject *co;
1712 PyObject *v; 1712 PyObject *v;
1713 long magic; 1713 long magic;
1714 long PyImport_GetMagicNumber(void); 1714 long PyImport_GetMagicNumber(void);
1715 1715
1716 magic = PyMarshal_ReadLongFromFile(fp); 1716 magic = PyMarshal_ReadLongFromFile(fp);
1717 if (magic != PyImport_GetMagicNumber()) { 1717 if (magic != PyImport_GetMagicNumber()) {
1718 PyErr_SetString(PyExc_RuntimeError, 1718 PyErr_SetString(PyExc_RuntimeError,
1719 "Bad magic number in .pyc file"); 1719 "Bad magic number in .pyc file");
1720 return NULL; 1720 return NULL;
1721 } 1721 }
1722 (void) PyMarshal_ReadLongFromFile(fp); 1722 (void) PyMarshal_ReadLongFromFile(fp);
1723 v = PyMarshal_ReadLastObjectFromFile(fp); 1723 v = PyMarshal_ReadLastObjectFromFile(fp);
1724 fclose(fp); 1724 fclose(fp);
1725 if (v == NULL || !PyCode_Check(v)) { 1725 if (v == NULL || !PyCode_Check(v)) {
1726 Py_XDECREF(v); 1726 Py_XDECREF(v);
1727 PyErr_SetString(PyExc_RuntimeError, 1727 PyErr_SetString(PyExc_RuntimeError,
1728 "Bad code object in .pyc file"); 1728 "Bad code object in .pyc file");
1729 return NULL; 1729 return NULL;
1730 } 1730 }
1731 co = (PyCodeObject *)v; 1731 co = (PyCodeObject *)v;
1732 v = PyEval_EvalCode(co, globals, locals); 1732 v = PyEval_EvalCode(co, globals, locals);
1733 if (v && flags) 1733 if (v && flags)
1734 flags->cf_flags |= (co->co_flags & PyCF_MASK); 1734 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1735 Py_DECREF(co); 1735 Py_DECREF(co);
1736 return v; 1736 return v;
1737 } 1737 }
1738 1738
1739 PyObject * 1739 PyObject *
1740 Py_CompileStringFlags(const char *str, const char *filename, int start, 1740 Py_CompileStringFlags(const char *str, const char *filename, int start,
1741 PyCompilerFlags *flags) 1741 PyCompilerFlags *flags)
1742 { 1742 {
1743 PyCodeObject *co; 1743 PyCodeObject *co;
1744 mod_ty mod; 1744 mod_ty mod;
1745 PyArena *arena = PyArena_New(); 1745 PyArena *arena = PyArena_New();
1746 if (arena == NULL) 1746 if (arena == NULL)
1747 return NULL; 1747 return NULL;
1748 1748
1749 mod = PyParser_ASTFromString(str, filename, start, flags, arena); 1749 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1750 if (mod == NULL) { 1750 if (mod == NULL) {
1751 PyArena_Free(arena); 1751 PyArena_Free(arena);
1752 return NULL; 1752 return NULL;
1753 } 1753 }
1754 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) { 1754 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1755 PyObject *result = PyAST_mod2obj(mod); 1755 PyObject *result = PyAST_mod2obj(mod);
1756 PyArena_Free(arena); 1756 PyArena_Free(arena);
1757 return result; 1757 return result;
1758 } 1758 }
1759 co = PyAST_Compile(mod, filename, flags, arena); 1759 co = PyAST_Compile(mod, filename, flags, arena);
1760 PyArena_Free(arena); 1760 PyArena_Free(arena);
1761 return (PyObject *)co; 1761 return (PyObject *)co;
1762 } 1762 }
1763 1763
1764 struct symtable * 1764 struct symtable *
1765 Py_SymtableString(const char *str, const char *filename, int start) 1765 Py_SymtableString(const char *str, const char *filename, int start)
1766 { 1766 {
1767 struct symtable *st; 1767 struct symtable *st;
1768 mod_ty mod; 1768 mod_ty mod;
1769 PyCompilerFlags flags; 1769 PyCompilerFlags flags;
1770 PyArena *arena = PyArena_New(); 1770 PyArena *arena = PyArena_New();
1771 if (arena == NULL) 1771 if (arena == NULL)
1772 return NULL; 1772 return NULL;
1773 1773
1774 flags.cf_flags = 0; 1774 flags.cf_flags = 0;
1775 mod = PyParser_ASTFromString(str, filename, start, &flags, arena); 1775 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1776 if (mod == NULL) { 1776 if (mod == NULL) {
1777 PyArena_Free(arena); 1777 PyArena_Free(arena);
1778 return NULL; 1778 return NULL;
1779 } 1779 }
1780 st = PySymtable_Build(mod, filename, 0); 1780 st = PySymtable_Build(mod, filename, 0);
1781 PyArena_Free(arena); 1781 PyArena_Free(arena);
1782 return st; 1782 return st;
1783 } 1783 }
1784 1784
1785 /* Preferred access to parser is through AST. */ 1785 /* Preferred access to parser is through AST. */
1786 mod_ty 1786 mod_ty
1787 PyParser_ASTFromString(const char *s, const char *filename, int start, 1787 PyParser_ASTFromString(const char *s, const char *filename, int start,
1788 PyCompilerFlags *flags, PyArena *arena) 1788 PyCompilerFlags *flags, PyArena *arena)
1789 { 1789 {
1790 mod_ty mod; 1790 mod_ty mod;
1791 PyCompilerFlags localflags; 1791 PyCompilerFlags localflags;
1792 perrdetail err; 1792 perrdetail err;
1793 int iflags = PARSER_FLAGS(flags); 1793 int iflags = PARSER_FLAGS(flags);
1794 1794
1795 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename, 1795 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1796 &_PyParser_Grammar, start, &err, 1796 &_PyParser_Grammar, start, &err,
1797 &iflags); 1797 &iflags);
1798 if (flags == NULL) { 1798 if (flags == NULL) {
1799 localflags.cf_flags = 0; 1799 localflags.cf_flags = 0;
1800 flags = &localflags; 1800 flags = &localflags;
1801 } 1801 }
1802 if (n) { 1802 if (n) {
1803 flags->cf_flags |= iflags & PyCF_MASK; 1803 flags->cf_flags |= iflags & PyCF_MASK;
1804 mod = PyAST_FromNode(n, flags, filename, arena); 1804 mod = PyAST_FromNode(n, flags, filename, arena);
1805 PyNode_Free(n); 1805 PyNode_Free(n);
1806 return mod; 1806 return mod;
1807 } 1807 }
1808 else { 1808 else {
1809 err_input(&err); 1809 err_input(&err);
1810 return NULL; 1810 return NULL;
1811 } 1811 }
1812 } 1812 }
1813 1813
1814 mod_ty 1814 mod_ty
1815 PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc, 1815 PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1816 int start, char *ps1, 1816 int start, char *ps1,
1817 char *ps2, PyCompilerFlags *flags, int *errcode, 1817 char *ps2, PyCompilerFlags *flags, int *errcode,
1818 PyArena *arena) 1818 PyArena *arena)
1819 { 1819 {
1820 mod_ty mod; 1820 mod_ty mod;
1821 PyCompilerFlags localflags; 1821 PyCompilerFlags localflags;
1822 perrdetail err; 1822 perrdetail err;
1823 int iflags = PARSER_FLAGS(flags); 1823 int iflags = PARSER_FLAGS(flags);
1824 1824
1825 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc, 1825 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1826 &_PyParser_Grammar, 1826 &_PyParser_Grammar,
1827 start, ps1, ps2, &err, &iflags); 1827 start, ps1, ps2, &err, &iflags);
1828 if (flags == NULL) { 1828 if (flags == NULL) {
1829 localflags.cf_flags = 0; 1829 localflags.cf_flags = 0;
1830 flags = &localflags; 1830 flags = &localflags;
1831 } 1831 }
1832 if (n) { 1832 if (n) {
1833 flags->cf_flags |= iflags & PyCF_MASK; 1833 flags->cf_flags |= iflags & PyCF_MASK;
1834 mod = PyAST_FromNode(n, flags, filename, arena); 1834 mod = PyAST_FromNode(n, flags, filename, arena);
1835 PyNode_Free(n); 1835 PyNode_Free(n);
1836 return mod; 1836 return mod;
1837 } 1837 }
1838 else { 1838 else {
1839 err_input(&err); 1839 err_input(&err);
1840 if (errcode) 1840 if (errcode)
1841 *errcode = err.error; 1841 *errcode = err.error;
1842 return NULL; 1842 return NULL;
1843 } 1843 }
1844 } 1844 }
1845 1845
1846 /* Simplified interface to parsefile -- return node or set exception */ 1846 /* Simplified interface to parsefile -- return node or set exception */
1847 1847
1848 node * 1848 node *
1849 PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) 1849 PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
1850 { 1850 {
1851 perrdetail err; 1851 perrdetail err;
1852 node *n = PyParser_ParseFileFlags(fp, filename, NULL, 1852 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1853 &_PyParser_Grammar, 1853 &_PyParser_Grammar,
1854 start, NULL, NULL, &err, flags); 1854 start, NULL, NULL, &err, flags);
1855 if (n == NULL) 1855 if (n == NULL)
1856 err_input(&err); 1856 err_input(&err);
1857 1857
1858 return n; 1858 return n;
1859 } 1859 }
1860 1860
1861 /* Simplified interface to parsestring -- return node or set exception */ 1861 /* Simplified interface to parsestring -- return node or set exception */
1862 1862
1863 node * 1863 node *
1864 PyParser_SimpleParseStringFlags(const char *str, int start, int flags) 1864 PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
1865 { 1865 {
1866 perrdetail err; 1866 perrdetail err;
1867 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, 1867 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1868 start, &err, flags); 1868 start, &err, flags);
1869 if (n == NULL) 1869 if (n == NULL)
1870 err_input(&err); 1870 err_input(&err);
1871 return n; 1871 return n;
1872 } 1872 }
1873 1873
1874 node * 1874 node *
1875 PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename, 1875 PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
1876 int start, int flags) 1876 int start, int flags)
1877 { 1877 {
1878 perrdetail err; 1878 perrdetail err;
1879 node *n = PyParser_ParseStringFlagsFilename(str, filename, 1879 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1880 &_PyParser_Grammar, start, &err, flags); 1880 &_PyParser_Grammar, start, &err, flags);
1881 if (n == NULL) 1881 if (n == NULL)
1882 err_input(&err); 1882 err_input(&err);
1883 return n; 1883 return n;
1884 } 1884 }
1885 1885
1886 node * 1886 node *
1887 PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start) 1887 PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
1888 { 1888 {
1889 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0); 1889 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
1890 } 1890 }
1891 1891
1892 /* May want to move a more generalized form of this to parsetok.c or 1892 /* May want to move a more generalized form of this to parsetok.c or
1893 even parser modules. */ 1893 even parser modules. */
1894 1894
1895 void 1895 void
1896 PyParser_SetError(perrdetail *err) 1896 PyParser_SetError(perrdetail *err)
1897 { 1897 {
1898 err_input(err); 1898 err_input(err);
1899 } 1899 }
1900 1900
1901 /* Set the error appropriate to the given input error code (see errcode.h) */ 1901 /* Set the error appropriate to the given input error code (see errcode.h) */
1902 1902
1903 static void 1903 static void
1904 err_input(perrdetail *err) 1904 err_input(perrdetail *err)
1905 { 1905 {
1906 PyObject *v, *w, *errtype, *errtext; 1906 PyObject *v, *w, *errtype, *errtext;
1907 PyObject* u = NULL; 1907 PyObject* u = NULL;
1908 char *msg = NULL; 1908 char *msg = NULL;
1909 errtype = PyExc_SyntaxError; 1909 errtype = PyExc_SyntaxError;
1910 switch (err->error) { 1910 switch (err->error) {
1911 case E_ERROR: 1911 case E_ERROR:
1912 return; 1912 return;
1913 case E_SYNTAX: 1913 case E_SYNTAX:
1914 errtype = PyExc_IndentationError; 1914 errtype = PyExc_IndentationError;
1915 if (err->expected == INDENT) 1915 if (err->expected == INDENT)
1916 msg = "expected an indented block"; 1916 msg = "expected an indented block";
1917 else if (err->token == INDENT) 1917 else if (err->token == INDENT)
1918 msg = "unexpected indent"; 1918 msg = "unexpected indent";
1919 else if (err->token == DEDENT) 1919 else if (err->token == DEDENT)
1920 msg = "unexpected unindent"; 1920 msg = "unexpected unindent";
1921 else { 1921 else {
1922 errtype = PyExc_SyntaxError; 1922 errtype = PyExc_SyntaxError;
1923 msg = "invalid syntax"; 1923 msg = "invalid syntax";
1924 } 1924 }
1925 break; 1925 break;
1926 case E_TOKEN: 1926 case E_TOKEN:
1927 msg = "invalid token"; 1927 msg = "invalid token";
1928 break; 1928 break;
1929 case E_EOFS: 1929 case E_EOFS:
1930 msg = "EOF while scanning triple-quoted string literal"; 1930 msg = "EOF while scanning triple-quoted string literal";
1931 break; 1931 break;
1932 case E_EOLS: 1932 case E_EOLS:
1933 msg = "EOL while scanning string literal"; 1933 msg = "EOL while scanning string literal";
1934 break; 1934 break;
1935 case E_INTR: 1935 case E_INTR:
1936 if (!PyErr_Occurred()) 1936 if (!PyErr_Occurred())
1937 PyErr_SetNone(PyExc_KeyboardInterrupt); 1937 PyErr_SetNone(PyExc_KeyboardInterrupt);
1938 goto cleanup; 1938 goto cleanup;
1939 case E_NOMEM: 1939 case E_NOMEM:
1940 PyErr_NoMemory(); 1940 PyErr_NoMemory();
1941 goto cleanup; 1941 goto cleanup;
1942 case E_EOF: 1942 case E_EOF:
1943 msg = "unexpected EOF while parsing"; 1943 msg = "unexpected EOF while parsing";
1944 break; 1944 break;
1945 case E_TABSPACE: 1945 case E_TABSPACE:
1946 errtype = PyExc_TabError; 1946 errtype = PyExc_TabError;
1947 msg = "inconsistent use of tabs and spaces in indentation"; 1947 msg = "inconsistent use of tabs and spaces in indentation";
1948 break; 1948 break;
1949 case E_OVERFLOW: 1949 case E_OVERFLOW:
1950 msg = "expression too long"; 1950 msg = "expression too long";
1951 break; 1951 break;
1952 case E_DEDENT: 1952 case E_DEDENT:
1953 errtype = PyExc_IndentationError; 1953 errtype = PyExc_IndentationError;
1954 msg = "unindent does not match any outer indentation level"; 1954 msg = "unindent does not match any outer indentation level";
1955 break; 1955 break;
1956 case E_TOODEEP: 1956 case E_TOODEEP:
1957 errtype = PyExc_IndentationError; 1957 errtype = PyExc_IndentationError;
1958 msg = "too many levels of indentation"; 1958 msg = "too many levels of indentation";
1959 break; 1959 break;
1960 case E_DECODE: { 1960 case E_DECODE: {
1961 PyObject *type, *value, *tb; 1961 PyObject *type, *value, *tb;
1962 PyErr_Fetch(&type, &value, &tb); 1962 PyErr_Fetch(&type, &value, &tb);
1963 if (value != NULL) { 1963 if (value != NULL) {
1964 u = PyObject_Str(value); 1964 u = PyObject_Str(value);
1965 if (u != NULL) { 1965 if (u != NULL) {
1966 msg = _PyUnicode_AsString(u); 1966 msg = _PyUnicode_AsString(u);
1967 } 1967 }
1968 } 1968 }
1969 if (msg == NULL) 1969 if (msg == NULL)
1970 msg = "unknown decode error"; 1970 msg = "unknown decode error";
1971 Py_XDECREF(type); 1971 Py_XDECREF(type);
1972 Py_XDECREF(value); 1972 Py_XDECREF(value);
1973 Py_XDECREF(tb); 1973 Py_XDECREF(tb);
1974 break; 1974 break;
1975 } 1975 }
1976 case E_LINECONT: 1976 case E_LINECONT:
1977 msg = "unexpected character after line continuation character"; 1977 msg = "unexpected character after line continuation character";
1978 break; 1978 break;
1979 1979
1980 case E_IDENTIFIER: 1980 case E_IDENTIFIER:
1981 msg = "invalid character in identifier"; 1981 msg = "invalid character in identifier";
1982 break; 1982 break;
1983 default: 1983 default:
1984 fprintf(stderr, "error=%d\n", err->error); 1984 fprintf(stderr, "error=%d\n", err->error);
1985 msg = "unknown parsing error"; 1985 msg = "unknown parsing error";
1986 break; 1986 break;
1987 } 1987 }
1988 /* err->text may not be UTF-8 in case of decoding errors. 1988 /* err->text may not be UTF-8 in case of decoding errors.
1989 Explicitly convert to an object. */ 1989 Explicitly convert to an object. */
1990 if (!err->text) { 1990 if (!err->text) {
1991 errtext = Py_None; 1991 errtext = Py_None;
1992 Py_INCREF(Py_None); 1992 Py_INCREF(Py_None);
1993 } else { 1993 } else {
1994 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text), 1994 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1995 "replace"); 1995 "replace");
1996 } 1996 }
1997 v = Py_BuildValue("(ziiN)", err->filename, 1997 v = Py_BuildValue("(ziiN)", err->filename,
1998 err->lineno, err->offset, errtext); 1998 err->lineno, err->offset, errtext);
1999 w = NULL; 1999 w = NULL;
2000 if (v != NULL) 2000 if (v != NULL)
2001 w = Py_BuildValue("(sO)", msg, v); 2001 w = Py_BuildValue("(sO)", msg, v);
2002 Py_XDECREF(u); 2002 Py_XDECREF(u);
2003 Py_XDECREF(v); 2003 Py_XDECREF(v);
2004 PyErr_SetObject(errtype, w); 2004 PyErr_SetObject(errtype, w);
2005 Py_XDECREF(w); 2005 Py_XDECREF(w);
2006 cleanup: 2006 cleanup:
2007 if (err->text != NULL) { 2007 if (err->text != NULL) {
2008 PyObject_FREE(err->text); 2008 PyObject_FREE(err->text);
2009 err->text = NULL; 2009 err->text = NULL;
2010 } 2010 }
2011 } 2011 }
2012 2012
2013 /* Print fatal error message and abort */ 2013 /* Print fatal error message and abort */
2014 2014
2015 void 2015 void
2016 Py_FatalError(const char *msg) 2016 Py_FatalError(const char *msg)
2017 { 2017 {
2018 fprintf(stderr, "Fatal Python error: %s\n", msg); 2018 fprintf(stderr, "Fatal Python error: %s\n", msg);
2019 fflush(stderr); /* it helps in Windows debug build */ 2019 fflush(stderr); /* it helps in Windows debug build */
2020 if (PyErr_Occurred()) { 2020 if (PyErr_Occurred()) {
2021 PyErr_Print(); 2021 PyErr_Print();
2022 } 2022 }
2023 #ifdef MS_WINDOWS 2023 #ifdef MS_WINDOWS
2024 { 2024 {
2025 size_t len = strlen(msg); 2025 size_t len = strlen(msg);
2026 WCHAR* buffer; 2026 WCHAR* buffer;
2027 size_t i; 2027 size_t i;
2028 2028
2029 /* Convert the message to wchar_t. This uses a simple one-to-one 2029 /* Convert the message to wchar_t. This uses a simple one-to-one
2030 conversion, assuming that the this error message actually uses ASCII 2030 conversion, assuming that the this error message actually uses ASCII
2031 only. If this ceases to be true, we will have to convert. */ 2031 only. If this ceases to be true, we will have to convert. */
2032 buffer = alloca( (len+1) * (sizeof *buffer)); 2032 buffer = alloca( (len+1) * (sizeof *buffer));
2033 for( i=0; i<=len; ++i) 2033 for( i=0; i<=len; ++i)
2034 buffer[i] = msg[i]; 2034 buffer[i] = msg[i];
2035 OutputDebugStringW(L"Fatal Python error: "); 2035 OutputDebugStringW(L"Fatal Python error: ");
2036 OutputDebugStringW(buffer); 2036 OutputDebugStringW(buffer);
2037 OutputDebugStringW(L"\n"); 2037 OutputDebugStringW(L"\n");
2038 } 2038 }
2039 #ifdef _DEBUG 2039 #ifdef _DEBUG
2040 DebugBreak(); 2040 DebugBreak();
2041 #endif 2041 #endif
2042 #endif /* MS_WINDOWS */ 2042 #endif /* MS_WINDOWS */
2043 abort(); 2043 abort();
2044 } 2044 }
2045 2045
2046 /* Clean up and exit */ 2046 /* Clean up and exit */
2047 2047
2048 #ifdef WITH_THREAD 2048 #ifdef WITH_THREAD
2051 2051
2052 static void (*pyexitfunc)(void) = NULL; 2052 static void (*pyexitfunc)(void) = NULL;
2053 /* For the atexit module. */ 2053 /* For the atexit module. */
2054 void _Py_PyAtExit(void (*func)(void)) 2054 void _Py_PyAtExit(void (*func)(void))
2055 { 2055 {
2056 pyexitfunc = func; 2056 pyexitfunc = func;
2057 } 2057 }
2058 2058
2059 static void 2059 static void
2060 call_py_exitfuncs(void) 2060 call_py_exitfuncs(void)
2061 { 2061 {
2062 if (pyexitfunc == NULL) 2062 if (pyexitfunc == NULL)
2063 return; 2063 return;
2064 2064
2065 (*pyexitfunc)(); 2065 (*pyexitfunc)();
2066 PyErr_Clear(); 2066 PyErr_Clear();
2067 } 2067 }
2068 2068
2069 /* Wait until threading._shutdown completes, provided 2069 /* Wait until threading._shutdown completes, provided
2070 the threading module was imported in the first place. 2070 the threading module was imported in the first place.
2071 The shutdown routine will wait until all non-daemon 2071 The shutdown routine will wait until all non-daemon
2072 "threading" threads have completed. */ 2072 "threading" threads have completed. */
2073 static void 2073 static void
2074 wait_for_thread_shutdown(void) 2074 wait_for_thread_shutdown(void)
2075 { 2075 {
2076 #ifdef WITH_THREAD 2076 #ifdef WITH_THREAD
2077 PyObject *result; 2077 PyObject *result;
2078 PyThreadState *tstate = PyThreadState_GET(); 2078 PyThreadState *tstate = PyThreadState_GET();
2079 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, 2079 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2080 "threading"); 2080 "threading");
2081 if (threading == NULL) { 2081 if (threading == NULL) {
2082 /* threading not imported */ 2082 /* threading not imported */
2083 PyErr_Clear(); 2083 PyErr_Clear();
2084 return; 2084 return;
2085 } 2085 }
2086 result = PyObject_CallMethod(threading, "_shutdown", ""); 2086 result = PyObject_CallMethod(threading, "_shutdown", "");
2087 if (result == NULL) { 2087 if (result == NULL) {
2088 PyErr_WriteUnraisable(threading); 2088 PyErr_WriteUnraisable(threading);
2089 } 2089 }
2090 else { 2090 else {
2091 Py_DECREF(result); 2091 Py_DECREF(result);
2092 } 2092 }
2093 Py_DECREF(threading); 2093 Py_DECREF(threading);
2094 #endif 2094 #endif
2095 } 2095 }
2096 2096
2097 #define NEXITFUNCS 32 2097 #define NEXITFUNCS 32
2098 static void (*exitfuncs[NEXITFUNCS])(void); 2098 static void (*exitfuncs[NEXITFUNCS])(void);
2099 static int nexitfuncs = 0; 2099 static int nexitfuncs = 0;
2100 2100
2101 int Py_AtExit(void (*func)(void)) 2101 int Py_AtExit(void (*func)(void))
2102 { 2102 {
2103 if (nexitfuncs >= NEXITFUNCS) 2103 if (nexitfuncs >= NEXITFUNCS)
2104 return -1; 2104 return -1;
2105 exitfuncs[nexitfuncs++] = func; 2105 exitfuncs[nexitfuncs++] = func;
2106 return 0; 2106 return 0;
2107 } 2107 }
2108 2108
2109 static void 2109 static void
2110 call_ll_exitfuncs(void) 2110 call_ll_exitfuncs(void)
2111 { 2111 {
2112 while (nexitfuncs > 0) 2112 while (nexitfuncs > 0)
2113 (*exitfuncs[--nexitfuncs])(); 2113 (*exitfuncs[--nexitfuncs])();
2114 2114
2115 fflush(stdout); 2115 fflush(stdout);
2116 fflush(stderr); 2116 fflush(stderr);
2117 } 2117 }
2118 2118
2119 void 2119 void
2120 Py_Exit(int sts) 2120 Py_Exit(int sts)
2121 { 2121 {
2122 Py_Finalize(); 2122 Py_Finalize();
2123 2123
2124 exit(sts); 2124 exit(sts);
2125 } 2125 }
2126 2126
2127 static void 2127 static void
2128 initsigs(void) 2128 initsigs(void)
2129 { 2129 {
2130 #ifdef SIGPIPE 2130 #ifdef SIGPIPE
2131 PyOS_setsig(SIGPIPE, SIG_IGN); 2131 PyOS_setsig(SIGPIPE, SIG_IGN);
2132 #endif 2132 #endif
2133 #ifdef SIGXFZ 2133 #ifdef SIGXFZ
2134 PyOS_setsig(SIGXFZ, SIG_IGN); 2134 PyOS_setsig(SIGXFZ, SIG_IGN);
2135 #endif 2135 #endif
2136 #ifdef SIGXFSZ 2136 #ifdef SIGXFSZ
2137 PyOS_setsig(SIGXFSZ, SIG_IGN); 2137 PyOS_setsig(SIGXFSZ, SIG_IGN);
2138 #endif 2138 #endif
2139 PyOS_InitInterrupts(); /* May imply initsignal() */ 2139 PyOS_InitInterrupts(); /* May imply initsignal() */
2140 } 2140 }
2141 2141
2142 2142
2143 /* 2143 /*
2144 * The file descriptor fd is considered ``interactive'' if either 2144 * The file descriptor fd is considered ``interactive'' if either
2147 * the descriptor is NULL or "<stdin>" or "???". 2147 * the descriptor is NULL or "<stdin>" or "???".
2148 */ 2148 */
2149 int 2149 int
2150 Py_FdIsInteractive(FILE *fp, const char *filename) 2150 Py_FdIsInteractive(FILE *fp, const char *filename)
2151 { 2151 {
2152 if (isatty((int)fileno(fp))) 2152 if (isatty((int)fileno(fp)))
2153 return 1; 2153 return 1;
2154 if (!Py_InteractiveFlag) 2154 if (!Py_InteractiveFlag)
2155 return 0; 2155 return 0;
2156 return (filename == NULL) || 2156 return (filename == NULL) ||
2157 (strcmp(filename, "<stdin>") == 0) || 2157 (strcmp(filename, "<stdin>") == 0) ||
2158 (strcmp(filename, "???") == 0); 2158 (strcmp(filename, "???") == 0);
2159 } 2159 }
2160 2160
2161 2161
2162 #if defined(USE_STACKCHECK) 2162 #if defined(USE_STACKCHECK)
2163 #if defined(WIN32) && defined(_MSC_VER) 2163 #if defined(WIN32) && defined(_MSC_VER)
2171 * Return non-zero when we run out of memory on the stack; zero otherwise. 2171 * Return non-zero when we run out of memory on the stack; zero otherwise.
2172 */ 2172 */
2173 int 2173 int
2174 PyOS_CheckStack(void) 2174 PyOS_CheckStack(void)
2175 { 2175 {
2176 __try { 2176 __try {
2177 /* alloca throws a stack overflow exception if there's 2177 /* alloca throws a stack overflow exception if there's
2178 not enough space left on the stack */ 2178 not enough space left on the stack */
2179 alloca(PYOS_STACK_MARGIN * sizeof(void*)); 2179 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2180 return 0; 2180 return 0;
2181 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? 2181 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2182 EXCEPTION_EXECUTE_HANDLER : 2182 EXCEPTION_EXECUTE_HANDLER :
2183 EXCEPTION_CONTINUE_SEARCH) { 2183 EXCEPTION_CONTINUE_SEARCH) {
2184 int errcode = _resetstkoflw(); 2184 int errcode = _resetstkoflw();
2185 if (errcode == 0) 2185 if (errcode == 0)
2186 { 2186 {
2187 Py_FatalError("Could not reset the stack!"); 2187 Py_FatalError("Could not reset the stack!");
2188 } 2188 }
2189 } 2189 }
2190 return 1; 2190 return 1;
2191 } 2191 }
2192 2192
2193 #endif /* WIN32 && _MSC_VER */ 2193 #endif /* WIN32 && _MSC_VER */
2194 2194
2195 /* Alternate implementations can be added here... */ 2195 /* Alternate implementations can be added here... */
2201 2201
2202 PyOS_sighandler_t 2202 PyOS_sighandler_t
2203 PyOS_getsig(int sig) 2203 PyOS_getsig(int sig)
2204 { 2204 {
2205 #ifdef HAVE_SIGACTION 2205 #ifdef HAVE_SIGACTION
2206 struct sigaction context; 2206 struct sigaction context;
2207 if (sigaction(sig, NULL, &context) == -1) 2207 if (sigaction(sig, NULL, &context) == -1)
2208 return SIG_ERR; 2208 return SIG_ERR;
2209 return context.sa_handler; 2209 return context.sa_handler;
2210 #else 2210 #else
2211 PyOS_sighandler_t handler; 2211 PyOS_sighandler_t handler;
2212 /* Special signal handling for the secure CRT in Visual Studio 2005 */ 2212 /* Special signal handling for the secure CRT in Visual Studio 2005 */
2213 #if defined(_MSC_VER) && _MSC_VER >= 1400 2213 #if defined(_MSC_VER) && _MSC_VER >= 1400
2214 switch (sig) { 2214 switch (sig) {
2215 /* Only these signals are valid */ 2215 /* Only these signals are valid */
2216 case SIGINT: 2216 case SIGINT:
2217 case SIGILL: 2217 case SIGILL:
2218 case SIGFPE: 2218 case SIGFPE:
2219 case SIGSEGV: 2219 case SIGSEGV:
2220 case SIGTERM: 2220 case SIGTERM:
2221 case SIGBREAK: 2221 case SIGBREAK:
2222 case SIGABRT: 2222 case SIGABRT:
2223 break; 2223 break;
2224 /* Don't call signal() with other values or it will assert */ 2224 /* Don't call signal() with other values or it will assert */
2225 default: 2225 default:
2226 return SIG_ERR; 2226 return SIG_ERR;
2227 } 2227 }
2228 #endif /* _MSC_VER && _MSC_VER >= 1400 */ 2228 #endif /* _MSC_VER && _MSC_VER >= 1400 */
2229 handler = signal(sig, SIG_IGN); 2229 handler = signal(sig, SIG_IGN);
2230 if (handler != SIG_ERR) 2230 if (handler != SIG_ERR)
2231 signal(sig, handler); 2231 signal(sig, handler);
2232 return handler; 2232 return handler;
2233 #endif 2233 #endif
2234 } 2234 }
2235 2235
2236 PyOS_sighandler_t 2236 PyOS_sighandler_t
2237 PyOS_setsig(int sig, PyOS_sighandler_t handler) 2237 PyOS_setsig(int sig, PyOS_sighandler_t handler)
2238 { 2238 {
2239 #ifdef HAVE_SIGACTION 2239 #ifdef HAVE_SIGACTION
2240 /* Some code in Modules/signalmodule.c depends on sigaction() being 2240 /* Some code in Modules/signalmodule.c depends on sigaction() being
2241 * used here if HAVE_SIGACTION is defined. Fix that if this code 2241 * used here if HAVE_SIGACTION is defined. Fix that if this code
2242 * changes to invalidate that assumption. 2242 * changes to invalidate that assumption.
2243 */ 2243 */
2244 struct sigaction context, ocontext; 2244 struct sigaction context, ocontext;
2245 context.sa_handler = handler; 2245 context.sa_handler = handler;
2246 sigemptyset(&context.sa_mask); 2246 sigemptyset(&context.sa_mask);
2247 context.sa_flags = 0; 2247 context.sa_flags = 0;
2248 if (sigaction(sig, &context, &ocontext) == -1) 2248 if (sigaction(sig, &context, &ocontext) == -1)
2249 return SIG_ERR; 2249 return SIG_ERR;
2250 return ocontext.sa_handler; 2250 return ocontext.sa_handler;
2251 #else 2251 #else
2252 PyOS_sighandler_t oldhandler; 2252 PyOS_sighandler_t oldhandler;
2253 oldhandler = signal(sig, handler); 2253 oldhandler = signal(sig, handler);
2254 #ifdef HAVE_SIGINTERRUPT 2254 #ifdef HAVE_SIGINTERRUPT
2255 siginterrupt(sig, 1); 2255 siginterrupt(sig, 1);
2256 #endif 2256 #endif
2257 return oldhandler; 2257 return oldhandler;
2258 #endif 2258 #endif
2259 } 2259 }
2260 2260
2261 /* Deprecated C API functions still provided for binary compatiblity */ 2261 /* Deprecated C API functions still provided for binary compatiblity */
2262 2262
2263 #undef PyParser_SimpleParseFile 2263 #undef PyParser_SimpleParseFile
2264 PyAPI_FUNC(node *) 2264 PyAPI_FUNC(node *)
2265 PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) 2265 PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2266 { 2266 {
2267 return PyParser_SimpleParseFileFlags(fp, filename, start, 0); 2267 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2268 } 2268 }
2269 2269
2270 #undef PyParser_SimpleParseString 2270 #undef PyParser_SimpleParseString
2271 PyAPI_FUNC(node *) 2271 PyAPI_FUNC(node *)
2272 PyParser_SimpleParseString(const char *str, int start) 2272 PyParser_SimpleParseString(const char *str, int start)
2273 { 2273 {
2274 return PyParser_SimpleParseStringFlags(str, start, 0); 2274 return PyParser_SimpleParseStringFlags(str, start, 0);
2275 } 2275 }
2276 2276
2277 #undef PyRun_AnyFile 2277 #undef PyRun_AnyFile
2278 PyAPI_FUNC(int) 2278 PyAPI_FUNC(int)
2279 PyRun_AnyFile(FILE *fp, const char *name) 2279 PyRun_AnyFile(FILE *fp, const char *name)
2280 { 2280 {
2281 return PyRun_AnyFileExFlags(fp, name, 0, NULL); 2281 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2282 } 2282 }
2283 2283
2284 #undef PyRun_AnyFileEx 2284 #undef PyRun_AnyFileEx
2285 PyAPI_FUNC(int) 2285 PyAPI_FUNC(int)
2286 PyRun_AnyFileEx(FILE *fp, const char *name, int closeit) 2286 PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2287 { 2287 {
2288 return PyRun_AnyFileExFlags(fp, name, closeit, NULL); 2288 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2289 } 2289 }
2290 2290
2291 #undef PyRun_AnyFileFlags 2291 #undef PyRun_AnyFileFlags
2292 PyAPI_FUNC(int) 2292 PyAPI_FUNC(int)
2293 PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags) 2293 PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2294 { 2294 {
2295 return PyRun_AnyFileExFlags(fp, name, 0, flags); 2295 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2296 } 2296 }
2297 2297
2298 #undef PyRun_File 2298 #undef PyRun_File
2299 PyAPI_FUNC(PyObject *) 2299 PyAPI_FUNC(PyObject *)
2300 PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l) 2300 PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2301 { 2301 {
2302 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL); 2302 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
2303 } 2303 }
2304 2304
2305 #undef PyRun_FileEx 2305 #undef PyRun_FileEx
2306 PyAPI_FUNC(PyObject *) 2306 PyAPI_FUNC(PyObject *)
2307 PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c) 2307 PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2308 { 2308 {
2309 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL); 2309 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
2310 } 2310 }
2311 2311
2312 #undef PyRun_FileFlags 2312 #undef PyRun_FileFlags
2313 PyAPI_FUNC(PyObject *) 2313 PyAPI_FUNC(PyObject *)
2314 PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, 2314 PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2315 PyCompilerFlags *flags) 2315 PyCompilerFlags *flags)
2316 { 2316 {
2317 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags); 2317 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
2318 } 2318 }
2319 2319
2320 #undef PyRun_SimpleFile 2320 #undef PyRun_SimpleFile
2321 PyAPI_FUNC(int) 2321 PyAPI_FUNC(int)
2322 PyRun_SimpleFile(FILE *f, const char *p) 2322 PyRun_SimpleFile(FILE *f, const char *p)
2323 { 2323 {
2324 return PyRun_SimpleFileExFlags(f, p, 0, NULL); 2324 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2325 } 2325 }
2326 2326
2327 #undef PyRun_SimpleFileEx 2327 #undef PyRun_SimpleFileEx
2328 PyAPI_FUNC(int) 2328 PyAPI_FUNC(int)
2329 PyRun_SimpleFileEx(FILE *f, const char *p, int c) 2329 PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2330 { 2330 {
2331 return PyRun_SimpleFileExFlags(f, p, c, NULL); 2331 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2332 } 2332 }
2333 2333
2334 2334
2335 #undef PyRun_String 2335 #undef PyRun_String
2336 PyAPI_FUNC(PyObject *) 2336 PyAPI_FUNC(PyObject *)
2337 PyRun_String(const char *str, int s, PyObject *g, PyObject *l) 2337 PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2338 { 2338 {
2339 return PyRun_StringFlags(str, s, g, l, NULL); 2339 return PyRun_StringFlags(str, s, g, l, NULL);
2340 } 2340 }
2341 2341
2342 #undef PyRun_SimpleString 2342 #undef PyRun_SimpleString
2343 PyAPI_FUNC(int) 2343 PyAPI_FUNC(int)
2344 PyRun_SimpleString(const char *s) 2344 PyRun_SimpleString(const char *s)
2345 { 2345 {
2346 return PyRun_SimpleStringFlags(s, NULL); 2346 return PyRun_SimpleStringFlags(s, NULL);
2347 } 2347 }
2348 2348
2349 #undef Py_CompileString 2349 #undef Py_CompileString
2350 PyAPI_FUNC(PyObject *) 2350 PyAPI_FUNC(PyObject *)
2351 Py_CompileString(const char *str, const char *p, int s) 2351 Py_CompileString(const char *str, const char *p, int s)
2352 { 2352 {
2353 return Py_CompileStringFlags(str, p, s, NULL); 2353 return Py_CompileStringFlags(str, p, s, NULL);
2354 } 2354 }
2355 2355
2356 #undef PyRun_InteractiveOne 2356 #undef PyRun_InteractiveOne
2357 PyAPI_FUNC(int) 2357 PyAPI_FUNC(int)
2358 PyRun_InteractiveOne(FILE *f, const char *p) 2358 PyRun_InteractiveOne(FILE *f, const char *p)
2359 { 2359 {
2360 return PyRun_InteractiveOneFlags(f, p, NULL); 2360 return PyRun_InteractiveOneFlags(f, p, NULL);
2361 } 2361 }
2362 2362
2363 #undef PyRun_InteractiveLoop 2363 #undef PyRun_InteractiveLoop
2364 PyAPI_FUNC(int) 2364 PyAPI_FUNC(int)
2365 PyRun_InteractiveLoop(FILE *f, const char *p) 2365 PyRun_InteractiveLoop(FILE *f, const char *p)
2366 { 2366 {
2367 return PyRun_InteractiveLoopFlags(f, p, NULL); 2367 return PyRun_InteractiveLoopFlags(f, p, NULL);
2368 } 2368 }
2369 2369
2370 #ifdef __cplusplus 2370 #ifdef __cplusplus
2371 } 2371 }
2372 #endif 2372 #endif