Python-2.7.3/Python/ceval.c

Location Tool Test ID Function Issue
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:794:11 gcc unused-but-set-variable PyEval_EvalFrameEx variable 'filename' set but not used
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:794:11 gcc unused-but-set-variable PyEval_EvalFrameEx variable 'filename' set but not used
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:794:11 gcc unused-but-set-variable PyEval_EvalFrameEx variable 'filename' set but not used
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:794:11 gcc unused-but-set-variable PyEval_EvalFrameEx variable 'filename' set but not used
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:1019:5 clang-analyzer Value stored to 'filename' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:1019:5 clang-analyzer Value stored to 'filename' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:1019:5 clang-analyzer Value stored to 'filename' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:1019:5 clang-analyzer Value stored to 'filename' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:2400:17 clang-analyzer Value stored to 'u' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:2400:17 clang-analyzer Value stored to 'u' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:2400:17 clang-analyzer Value stored to 'u' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:2400:17 clang-analyzer Value stored to 'u' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:2400:17 clang-analyzer Value stored to 'u' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:2400:17 clang-analyzer Value stored to 'u' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:2400:17 clang-analyzer Value stored to 'u' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:2400:17 clang-analyzer Value stored to 'u' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:3064:17 clang-analyzer Value stored to 'why' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:3064:17 clang-analyzer Value stored to 'why' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:3064:17 clang-analyzer Value stored to 'why' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:3064:17 clang-analyzer Value stored to 'why' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:3064:17 clang-analyzer Value stored to 'why' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:3064:17 clang-analyzer Value stored to 'why' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:3064:17 clang-analyzer Value stored to 'why' is never read
/builddir/build/BUILD/Python-2.7.3/Python/ceval.c:3064:17 clang-analyzer Value stored to 'why' is never read
   1 /* Execute compiled code */
   2 
   3 /* XXX TO DO:
   4    XXX speed up searching for keywords by using a dictionary
   5    XXX document it!
   6    */
   7 
   8 /* enable more aggressive intra-module optimizations, where available */
   9 #define PY_LOCAL_AGGRESSIVE
  10 
  11 #include "Python.h"
  12 
  13 #include "code.h"
  14 #include "frameobject.h"
  15 #include "eval.h"
  16 #include "opcode.h"
  17 #include "structmember.h"
  18 
  19 #include <ctype.h>
  20 
  21 #ifdef WITH_DTRACE
  22 #include "pydtrace.h"
  23 #endif
  24 
  25 #ifndef WITH_TSC
  26 
  27 #define READ_TIMESTAMP(var)
  28 
  29 #else
  30 
  31 typedef unsigned long long uint64;
  32 
  33 /* PowerPC support.
  34    "__ppc__" appears to be the preprocessor definition to detect on OS X, whereas
  35    "__powerpc__" appears to be the correct one for Linux with GCC
  36 */
  37 #if defined(__ppc__) || defined (__powerpc__)
  38 
  39 #if defined( __powerpc64__) || defined(__LP64__)
  40 /* 64-bit PowerPC */
  41 #define READ_TIMESTAMP(var) ppc64_getcounter(&var)
  42 static void
  43 ppc64_getcounter(uint64 *v)
  44 {
  45     /* On 64-bit PowerPC we can read the 64-bit timebase directly into a
  46        64-bit register */
  47     uint64 timebase;
  48 #ifdef _ARCH_PWR4
  49     asm volatile ("mfspr %0,268" : "=r" (timebase));
  50 #else
  51     asm volatile ("mftb %0" : "=r" (timebase));
  52 #endif
  53     *v = timebase;
  54 }
  55 
  56 #else
  57 /* 32-bit PowerPC */
  58 #define READ_TIMESTAMP(var) ppc32_getcounter(&var)
  59 
  60 static void
  61 ppc32_getcounter(uint64 *v)
  62 {
  63     union { long long ll; long ii[2]; } u;
  64     long tmp;
  65 
  66   loop:
  67     asm volatile ("mftbu %0" : "=r" (u.ii[0]) );
  68     asm volatile ("mftb  %0" : "=r" (u.ii[1]) );
  69     asm volatile ("mftbu %0" : "=r" (tmp));
  70     if (__builtin_expect(u.ii[0] != tmp, 0)) goto loop;
  71 
  72     *v = u.ll;
  73 }
  74 #endif /* powerpc 32/64 bit */
  75 
  76 #elif defined(__i386__)
  77 
  78 /* this is for linux/x86 (and probably any other GCC/x86 combo) */
  79 
  80 #define READ_TIMESTAMP(val) \
  81      __asm__ __volatile__("rdtsc" : "=A" (val))
  82 
  83 #elif defined(__x86_64__)
  84 
  85 /* for gcc/x86_64, the "A" constraint in DI mode means *either* rax *or* rdx;
  86    not edx:eax as it does for i386.  Since rdtsc puts its result in edx:eax
  87    even in 64-bit mode, we need to use "a" and "d" for the lower and upper
  88    32-bit pieces of the result. */
  89 
  90 #define READ_TIMESTAMP(val) \
  91     __asm__ __volatile__("rdtsc" : \
  92                          "=a" (((int*)&(val))[0]), "=d" (((int*)&(val))[1]));
  93 
  94 
  95 #else
  96 
  97 #error "Don't know how to implement timestamp counter for this architecture"
  98 
  99 #endif
 100 
 101 void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1,
 102               uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1)
 103 {
 104     uint64 intr, inst, loop;
 105     PyThreadState *tstate = PyThreadState_Get();
 106     if (!tstate->interp->tscdump)
 107         return;
 108     intr = intr1 - intr0;
 109     inst = inst1 - inst0 - intr;
 110     loop = loop1 - loop0 - intr;
 111     fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n",
 112             opcode, ticked, inst, loop);
 113 }
 114 
 115 #endif
 116 
 117 /* Turn this on if your compiler chokes on the big switch: */
 118 /* #define CASE_TOO_BIG 1 */
 119 
 120 #ifdef Py_DEBUG
 121 /* For debugging the interpreter: */
 122 #define LLTRACE  1      /* Low-level trace feature */
 123 #define CHECKEXC 1      /* Double-check exception checking */
 124 #endif
 125 
 126 typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *);
 127 
 128 /* Forward declarations */
 129 #ifdef WITH_TSC
 130 static PyObject * call_function(PyObject ***, int, uint64*, uint64*);
 131 #else
 132 static PyObject * call_function(PyObject ***, int);
 133 #endif
 134 static PyObject * fast_function(PyObject *, PyObject ***, int, int, int);
 135 static PyObject * do_call(PyObject *, PyObject ***, int, int);
 136 static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int);
 137 static PyObject * update_keyword_args(PyObject *, int, PyObject ***,
 138                                       PyObject *);
 139 static PyObject * update_star_args(int, int, PyObject *, PyObject ***);
 140 static PyObject * load_args(PyObject ***, int);
 141 #define CALL_FLAG_VAR 1
 142 #define CALL_FLAG_KW 2
 143 
 144 #ifdef LLTRACE
 145 static int lltrace;
 146 static int prtrace(PyObject *, char *);
 147 #endif
 148 static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *,
 149                       int, PyObject *);
 150 static int call_trace_protected(Py_tracefunc, PyObject *,
 151                                 PyFrameObject *, int, PyObject *);
 152 static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *);
 153 static int maybe_call_line_trace(Py_tracefunc, PyObject *,
 154                                  PyFrameObject *, int *, int *, int *);
 155 
 156 static PyObject * apply_slice(PyObject *, PyObject *, PyObject *);
 157 static int assign_slice(PyObject *, PyObject *,
 158                         PyObject *, PyObject *);
 159 static PyObject * cmp_outcome(int, PyObject *, PyObject *);
 160 static PyObject * import_from(PyObject *, PyObject *);
 161 static int import_all_from(PyObject *, PyObject *);
 162 static PyObject * build_class(PyObject *, PyObject *, PyObject *);
 163 static int exec_statement(PyFrameObject *,
 164                           PyObject *, PyObject *, PyObject *);
 165 static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *);
 166 static void reset_exc_info(PyThreadState *);
 167 static void format_exc_check_arg(PyObject *, char *, PyObject *);
 168 static PyObject * string_concatenate(PyObject *, PyObject *,
 169                                      PyFrameObject *, unsigned char *);
 170 static PyObject * kwd_as_string(PyObject *);
 171 static PyObject * special_lookup(PyObject *, char *, PyObject **);
 172 
 173 #define NAME_ERROR_MSG \
 174     "name '%.200s' is not defined"
 175 #define GLOBAL_NAME_ERROR_MSG \
 176     "global name '%.200s' is not defined"
 177 #define UNBOUNDLOCAL_ERROR_MSG \
 178     "local variable '%.200s' referenced before assignment"
 179 #define UNBOUNDFREE_ERROR_MSG \
 180     "free variable '%.200s' referenced before assignment" \
 181     " in enclosing scope"
 182 
 183 /* Dynamic execution profile */
 184 #ifdef DYNAMIC_EXECUTION_PROFILE
 185 #ifdef DXPAIRS
 186 static long dxpairs[257][256];
 187 #define dxp dxpairs[256]
 188 #else
 189 static long dxp[256];
 190 #endif
 191 #endif
 192 
 193 /* Function call profile */
 194 #ifdef CALL_PROFILE
 195 #define PCALL_NUM 11
 196 static int pcall[PCALL_NUM];
 197 
 198 #define PCALL_ALL 0
 199 #define PCALL_FUNCTION 1
 200 #define PCALL_FAST_FUNCTION 2
 201 #define PCALL_FASTER_FUNCTION 3
 202 #define PCALL_METHOD 4
 203 #define PCALL_BOUND_METHOD 5
 204 #define PCALL_CFUNCTION 6
 205 #define PCALL_TYPE 7
 206 #define PCALL_GENERATOR 8
 207 #define PCALL_OTHER 9
 208 #define PCALL_POP 10
 209 
 210 /* Notes about the statistics
 211 
 212    PCALL_FAST stats
 213 
 214    FAST_FUNCTION means no argument tuple needs to be created.
 215    FASTER_FUNCTION means that the fast-path frame setup code is used.
 216 
 217    If there is a method call where the call can be optimized by changing
 218    the argument tuple and calling the function directly, it gets recorded
 219    twice.
 220 
 221    As a result, the relationship among the statistics appears to be
 222    PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD +
 223                 PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER
 224    PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION
 225    PCALL_METHOD > PCALL_BOUND_METHOD
 226 */
 227 
 228 #define PCALL(POS) pcall[POS]++
 229 
 230 PyObject *
 231 PyEval_GetCallStats(PyObject *self)
 232 {
 233     return Py_BuildValue("iiiiiiiiiii",
 234                          pcall[0], pcall[1], pcall[2], pcall[3],
 235                          pcall[4], pcall[5], pcall[6], pcall[7],
 236                          pcall[8], pcall[9], pcall[10]);
 237 }
 238 #else
 239 #define PCALL(O)
 240 
 241 PyObject *
 242 PyEval_GetCallStats(PyObject *self)
 243 {
 244     Py_INCREF(Py_None);
 245     return Py_None;
 246 }
 247 #endif
 248 
 249 
 250 #ifdef WITH_THREAD
 251 
 252 #ifdef HAVE_ERRNO_H
 253 #include <errno.h>
 254 #endif
 255 #include "pythread.h"
 256 
 257 static PyThread_type_lock interpreter_lock = 0; /* This is the GIL */
 258 static PyThread_type_lock pending_lock = 0; /* for pending calls */
 259 static long main_thread = 0;
 260 
 261 int
 262 PyEval_ThreadsInitialized(void)
 263 {
 264     return interpreter_lock != 0;
 265 }
 266 
 267 void
 268 PyEval_InitThreads(void)
 269 {
 270     if (interpreter_lock)
 271         return;
 272     interpreter_lock = PyThread_allocate_lock();
 273     PyThread_acquire_lock(interpreter_lock, 1);
 274     main_thread = PyThread_get_thread_ident();
 275 }
 276 
 277 void
 278 PyEval_AcquireLock(void)
 279 {
 280     PyThread_acquire_lock(interpreter_lock, 1);
 281 }
 282 
 283 void
 284 PyEval_ReleaseLock(void)
 285 {
 286     PyThread_release_lock(interpreter_lock);
 287 }
 288 
 289 void
 290 PyEval_AcquireThread(PyThreadState *tstate)
 291 {
 292     if (tstate == NULL)
 293         Py_FatalError("PyEval_AcquireThread: NULL new thread state");
 294     /* Check someone has called PyEval_InitThreads() to create the lock */
 295     assert(interpreter_lock);
 296     PyThread_acquire_lock(interpreter_lock, 1);
 297     if (PyThreadState_Swap(tstate) != NULL)
 298         Py_FatalError(
 299             "PyEval_AcquireThread: non-NULL old thread state");
 300 }
 301 
 302 void
 303 PyEval_ReleaseThread(PyThreadState *tstate)
 304 {
 305     if (tstate == NULL)
 306         Py_FatalError("PyEval_ReleaseThread: NULL thread state");
 307     if (PyThreadState_Swap(NULL) != tstate)
 308         Py_FatalError("PyEval_ReleaseThread: wrong thread state");
 309     PyThread_release_lock(interpreter_lock);
 310 }
 311 
 312 /* This function is called from PyOS_AfterFork to ensure that newly
 313    created child processes don't hold locks referring to threads which
 314    are not running in the child process.  (This could also be done using
 315    pthread_atfork mechanism, at least for the pthreads implementation.) */
 316 
 317 void
 318 PyEval_ReInitThreads(void)
 319 {
 320     PyObject *threading, *result;
 321     PyThreadState *tstate;
 322 
 323     if (!interpreter_lock)
 324         return;
 325     /*XXX Can't use PyThread_free_lock here because it does too
 326       much error-checking.  Doing this cleanly would require
 327       adding a new function to each thread_*.h.  Instead, just
 328       create a new lock and waste a little bit of memory */
 329     interpreter_lock = PyThread_allocate_lock();
 330     pending_lock = PyThread_allocate_lock();
 331     PyThread_acquire_lock(interpreter_lock, 1);
 332     main_thread = PyThread_get_thread_ident();
 333 
 334     /* Update the threading module with the new state.
 335      */
 336     tstate = PyThreadState_GET();
 337     threading = PyMapping_GetItemString(tstate->interp->modules,
 338                                         "threading");
 339     if (threading == NULL) {
 340         /* threading not imported */
 341         PyErr_Clear();
 342         return;
 343     }
 344     result = PyObject_CallMethod(threading, "_after_fork", NULL);
 345     if (result == NULL)
 346         PyErr_WriteUnraisable(threading);
 347     else
 348         Py_DECREF(result);
 349     Py_DECREF(threading);
 350 }
 351 #endif
 352 
 353 /* Functions save_thread and restore_thread are always defined so
 354    dynamically loaded modules needn't be compiled separately for use
 355    with and without threads: */
 356 
 357 PyThreadState *
 358 PyEval_SaveThread(void)
 359 {
 360     PyThreadState *tstate = PyThreadState_Swap(NULL);
 361     if (tstate == NULL)
 362         Py_FatalError("PyEval_SaveThread: NULL tstate");
 363 #ifdef WITH_THREAD
 364     if (interpreter_lock)
 365         PyThread_release_lock(interpreter_lock);
 366 #endif
 367     return tstate;
 368 }
 369 
 370 void
 371 PyEval_RestoreThread(PyThreadState *tstate)
 372 {
 373     if (tstate == NULL)
 374         Py_FatalError("PyEval_RestoreThread: NULL tstate");
 375 #ifdef WITH_THREAD
 376     if (interpreter_lock) {
 377         int err = errno;
 378         PyThread_acquire_lock(interpreter_lock, 1);
 379         errno = err;
 380     }
 381 #endif
 382     PyThreadState_Swap(tstate);
 383 }
 384 
 385 
 386 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
 387    signal handlers or Mac I/O completion routines) can schedule calls
 388    to a function to be called synchronously.
 389    The synchronous function is called with one void* argument.
 390    It should return 0 for success or -1 for failure -- failure should
 391    be accompanied by an exception.
 392 
 393    If registry succeeds, the registry function returns 0; if it fails
 394    (e.g. due to too many pending calls) it returns -1 (without setting
 395    an exception condition).
 396 
 397    Note that because registry may occur from within signal handlers,
 398    or other asynchronous events, calling malloc() is unsafe!
 399 
 400 #ifdef WITH_THREAD
 401    Any thread can schedule pending calls, but only the main thread
 402    will execute them.
 403    There is no facility to schedule calls to a particular thread, but
 404    that should be easy to change, should that ever be required.  In
 405    that case, the static variables here should go into the python
 406    threadstate.
 407 #endif
 408 */
 409 
 410 #ifdef WITH_THREAD
 411 
 412 /* The WITH_THREAD implementation is thread-safe.  It allows
 413    scheduling to be made from any thread, and even from an executing
 414    callback.
 415  */
 416 
 417 #define NPENDINGCALLS 32
 418 static struct {
 419     int (*func)(void *);
 420     void *arg;
 421 } pendingcalls[NPENDINGCALLS];
 422 static int pendingfirst = 0;
 423 static int pendinglast = 0;
 424 static volatile int pendingcalls_to_do = 1; /* trigger initialization of lock */
 425 static char pendingbusy = 0;
 426 
 427 int
 428 Py_AddPendingCall(int (*func)(void *), void *arg)
 429 {
 430     int i, j, result=0;
 431     PyThread_type_lock lock = pending_lock;
 432 
 433     /* try a few times for the lock.  Since this mechanism is used
 434      * for signal handling (on the main thread), there is a (slim)
 435      * chance that a signal is delivered on the same thread while we
 436      * hold the lock during the Py_MakePendingCalls() function.
 437      * This avoids a deadlock in that case.
 438      * Note that signals can be delivered on any thread.  In particular,
 439      * on Windows, a SIGINT is delivered on a system-created worker
 440      * thread.
 441      * We also check for lock being NULL, in the unlikely case that
 442      * this function is called before any bytecode evaluation takes place.
 443      */
 444     if (lock != NULL) {
 445         for (i = 0; i<100; i++) {
 446             if (PyThread_acquire_lock(lock, NOWAIT_LOCK))
 447                 break;
 448         }
 449         if (i == 100)
 450             return -1;
 451     }
 452 
 453     i = pendinglast;
 454     j = (i + 1) % NPENDINGCALLS;
 455     if (j == pendingfirst) {
 456         result = -1; /* Queue full */
 457     } else {
 458         pendingcalls[i].func = func;
 459         pendingcalls[i].arg = arg;
 460         pendinglast = j;
 461     }
 462     /* signal main loop */
 463     _Py_Ticker = 0;
 464     pendingcalls_to_do = 1;
 465     if (lock != NULL)
 466         PyThread_release_lock(lock);
 467     return result;
 468 }
 469 
 470 int
 471 Py_MakePendingCalls(void)
 472 {
 473     int i;
 474     int r = 0;
 475 
 476     if (!pending_lock) {
 477         /* initial allocation of the lock */
 478         pending_lock = PyThread_allocate_lock();
 479         if (pending_lock == NULL)
 480             return -1;
 481     }
 482 
 483     /* only service pending calls on main thread */
 484     if (main_thread && PyThread_get_thread_ident() != main_thread)
 485         return 0;
 486     /* don't perform recursive pending calls */
 487     if (pendingbusy)
 488         return 0;
 489     pendingbusy = 1;
 490     /* perform a bounded number of calls, in case of recursion */
 491     for (i=0; i<NPENDINGCALLS; i++) {
 492         int j;
 493         int (*func)(void *);
 494         void *arg = NULL;
 495 
 496         /* pop one item off the queue while holding the lock */
 497         PyThread_acquire_lock(pending_lock, WAIT_LOCK);
 498         j = pendingfirst;
 499         if (j == pendinglast) {
 500             func = NULL; /* Queue empty */
 501         } else {
 502             func = pendingcalls[j].func;
 503             arg = pendingcalls[j].arg;
 504             pendingfirst = (j + 1) % NPENDINGCALLS;
 505         }
 506         pendingcalls_to_do = pendingfirst != pendinglast;
 507         PyThread_release_lock(pending_lock);
 508         /* having released the lock, perform the callback */
 509         if (func == NULL)
 510             break;
 511         r = func(arg);
 512         if (r)
 513             break;
 514     }
 515     pendingbusy = 0;
 516     return r;
 517 }
 518 
 519 #else /* if ! defined WITH_THREAD */
 520 
 521 /*
 522    WARNING!  ASYNCHRONOUSLY EXECUTING CODE!
 523    This code is used for signal handling in python that isn't built
 524    with WITH_THREAD.
 525    Don't use this implementation when Py_AddPendingCalls() can happen
 526    on a different thread!
 527 
 528    There are two possible race conditions:
 529    (1) nested asynchronous calls to Py_AddPendingCall()
 530    (2) AddPendingCall() calls made while pending calls are being processed.
 531 
 532    (1) is very unlikely because typically signal delivery
 533    is blocked during signal handling.  So it should be impossible.
 534    (2) is a real possibility.
 535    The current code is safe against (2), but not against (1).
 536    The safety against (2) is derived from the fact that only one
 537    thread is present, interrupted by signals, and that the critical
 538    section is protected with the "busy" variable.  On Windows, which
 539    delivers SIGINT on a system thread, this does not hold and therefore
 540    Windows really shouldn't use this version.
 541    The two threads could theoretically wiggle around the "busy" variable.
 542 */
 543 
 544 #define NPENDINGCALLS 32
 545 static struct {
 546     int (*func)(void *);
 547     void *arg;
 548 } pendingcalls[NPENDINGCALLS];
 549 static volatile int pendingfirst = 0;
 550 static volatile int pendinglast = 0;
 551 static volatile int pendingcalls_to_do = 0;
 552 
 553 int
 554 Py_AddPendingCall(int (*func)(void *), void *arg)
 555 {
 556     static volatile int busy = 0;
 557     int i, j;
 558     /* XXX Begin critical section */
 559     if (busy)
 560         return -1;
 561     busy = 1;
 562     i = pendinglast;
 563     j = (i + 1) % NPENDINGCALLS;
 564     if (j == pendingfirst) {
 565         busy = 0;
 566         return -1; /* Queue full */
 567     }
 568     pendingcalls[i].func = func;
 569     pendingcalls[i].arg = arg;
 570     pendinglast = j;
 571 
 572     _Py_Ticker = 0;
 573     pendingcalls_to_do = 1; /* Signal main loop */
 574     busy = 0;
 575     /* XXX End critical section */
 576     return 0;
 577 }
 578 
 579 int
 580 Py_MakePendingCalls(void)
 581 {
 582     static int busy = 0;
 583     if (busy)
 584         return 0;
 585     busy = 1;
 586     pendingcalls_to_do = 0;
 587     for (;;) {
 588         int i;
 589         int (*func)(void *);
 590         void *arg;
 591         i = pendingfirst;
 592         if (i == pendinglast)
 593             break; /* Queue empty */
 594         func = pendingcalls[i].func;
 595         arg = pendingcalls[i].arg;
 596         pendingfirst = (i + 1) % NPENDINGCALLS;
 597         if (func(arg) < 0) {
 598             busy = 0;
 599             pendingcalls_to_do = 1; /* We're not done yet */
 600             return -1;
 601         }
 602     }
 603     busy = 0;
 604     return 0;
 605 }
 606 
 607 #endif /* WITH_THREAD */
 608 
 609 
 610 /* The interpreter's recursion limit */
 611 
 612 #ifndef Py_DEFAULT_RECURSION_LIMIT
 613 #define Py_DEFAULT_RECURSION_LIMIT 1000
 614 #endif
 615 static int recursion_limit = Py_DEFAULT_RECURSION_LIMIT;
 616 int _Py_CheckRecursionLimit = Py_DEFAULT_RECURSION_LIMIT;
 617 
 618 int
 619 Py_GetRecursionLimit(void)
 620 {
 621     return recursion_limit;
 622 }
 623 
 624 void
 625 Py_SetRecursionLimit(int new_limit)
 626 {
 627     recursion_limit = new_limit;
 628     _Py_CheckRecursionLimit = recursion_limit;
 629 }
 630 
 631 /* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
 632    if the recursion_depth reaches _Py_CheckRecursionLimit.
 633    If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit
 634    to guarantee that _Py_CheckRecursiveCall() is regularly called.
 635    Without USE_STACKCHECK, there is no need for this. */
 636 int
 637 _Py_CheckRecursiveCall(char *where)
 638 {
 639     PyThreadState *tstate = PyThreadState_GET();
 640 
 641 #ifdef USE_STACKCHECK
 642     if (PyOS_CheckStack()) {
 643         --tstate->recursion_depth;
 644         PyErr_SetString(PyExc_MemoryError, "Stack overflow");
 645         return -1;
 646     }
 647 #endif
 648     if (tstate->recursion_depth > recursion_limit) {
 649         --tstate->recursion_depth;
 650         PyErr_Format(PyExc_RuntimeError,
 651                      "maximum recursion depth exceeded%s",
 652                      where);
 653         return -1;
 654     }
 655     _Py_CheckRecursionLimit = recursion_limit;
 656     return 0;
 657 }
 658 
 659 /* Status code for main loop (reason for stack unwind) */
 660 enum why_code {
 661         WHY_NOT =       0x0001, /* No error */
 662         WHY_EXCEPTION = 0x0002, /* Exception occurred */
 663         WHY_RERAISE =   0x0004, /* Exception re-raised by 'finally' */
 664         WHY_RETURN =    0x0008, /* 'return' statement */
 665         WHY_BREAK =     0x0010, /* 'break' statement */
 666         WHY_CONTINUE =  0x0020, /* 'continue' statement */
 667         WHY_YIELD =     0x0040  /* 'yield' operator */
 668 };
 669 
 670 static enum why_code do_raise(PyObject *, PyObject *, PyObject *);
 671 static int unpack_iterable(PyObject *, int, PyObject **);
 672 
 673 /* Records whether tracing is on for any thread.  Counts the number of
 674    threads for which tstate->c_tracefunc is non-NULL, so if the value
 675    is 0, we know we don't have to check this thread's c_tracefunc.
 676    This speeds up the if statement in PyEval_EvalFrameEx() after
 677    fast_next_opcode*/
 678 static int _Py_TracingPossible = 0;
 679 
 680 /* for manipulating the thread switch and periodic "stuff" - used to be
 681    per thread, now just a pair o' globals */
 682 int _Py_CheckInterval = 100;
 683 volatile int _Py_Ticker = 0; /* so that we hit a "tick" first thing */
 684 
 685 PyObject *
 686 PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
 687 {
 688     return PyEval_EvalCodeEx(co,
 689                       globals, locals,
 690                       (PyObject **)NULL, 0,
 691                       (PyObject **)NULL, 0,
 692                       (PyObject **)NULL, 0,
 693                       NULL);
 694 }
 695 
 696 #ifdef WITH_DTRACE
 697 static void
 698 dtrace_entry(PyFrameObject *f)
 699 {
 700     const char *filename;
 701     const char *fname;
 702     int lineno;
 703 
 704     filename = PyString_AsString(f->f_code->co_filename);
 705     fname = PyString_AsString(f->f_code->co_name);
 706     lineno = PyCode_Addr2Line(f->f_code, f->f_lasti);
 707 
 708     PYTHON_FUNCTION_ENTRY((char *)filename, (char *)fname, lineno);
 709 
 710     /*
 711      * Currently a USDT tail-call will not receive the correct arguments.
 712      * Disable the tail call here.
 713      */
 714 #if defined(__sparc)
 715     asm("nop");
 716 #endif
 717 }
 718 
 719 static void
 720 dtrace_return(PyFrameObject *f)
 721 {
 722     const char *filename;
 723     const char *fname;
 724     int lineno;
 725 
 726     filename = PyString_AsString(f->f_code->co_filename);
 727     fname = PyString_AsString(f->f_code->co_name);
 728     lineno = PyCode_Addr2Line(f->f_code, f->f_lasti);
 729     PYTHON_FUNCTION_RETURN((char *)filename, (char *)fname, lineno);
 730 
 731     /*
 732      * Currently a USDT tail-call will not receive the correct arguments.
 733      * Disable the tail call here.
 734      */
 735 #if defined(__sparc)
 736     asm("nop");
 737 #endif
 738 }
 739 #else
 740 #define	PYTHON_FUNCTION_ENTRY_ENABLED() 0
 741 #define	PYTHON_FUNCTION_RETURN_ENABLED() 0
 742 #define	dtrace_entry(f)
 743 #define	dtrace_return(f)
 744 #endif
 745 
 746 /* Interpreter main loop */
 747 
 748 PyObject *
 749 PyEval_EvalFrame(PyFrameObject *f) {
 750     /* This is for backward compatibility with extension modules that
 751        used this API; core interpreter code should call
 752        PyEval_EvalFrameEx() */
 753     return PyEval_EvalFrameEx(f, 0);
 754 }
 755 
 756 PyObject *
 757 PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
 758 {
 759 #ifdef DXPAIRS
 760     int lastopcode = 0;
 761 #endif
 762     register PyObject **stack_pointer;  /* Next free slot in value stack */
 763     register unsigned char *next_instr;
 764     register int opcode;        /* Current opcode */
 765     register int oparg;         /* Current opcode argument, if any */
 766     register enum why_code why; /* Reason for block stack unwind */
 767     register int err;           /* Error status -- nonzero if error */
 768     register PyObject *x;       /* Result object -- NULL if error */
 769     register PyObject *v;       /* Temporary objects popped off stack */
 770     register PyObject *w;
 771     register PyObject *u;
 772     register PyObject *t;
 773     register PyObject *stream = NULL;    /* for PRINT opcodes */
 774     register PyObject **fastlocals, **freevars;
 775     PyObject *retval = NULL;            /* Return value */
 776     PyThreadState *tstate = PyThreadState_GET();
 777     PyCodeObject *co;
 778 
 779     /* when tracing we set things up so that
 780 
 781            not (instr_lb <= current_bytecode_offset < instr_ub)
 782 
 783        is true when the line being executed has changed.  The
 784        initial values are such as to make this false the first
 785        time it is tested. */
 786     int instr_ub = -1, instr_lb = 0, instr_prev = -1;
 787 
 788     unsigned char *first_instr;
 789     PyObject *names;
 790     PyObject *consts;
 791 #if defined(Py_DEBUG) || defined(LLTRACE)
 792     /* Make it easier to find out where we are with a debugger */
 793     char *filename;
 794 #endif
variable 'filename' set but not used
(emitted by gcc)
variable 'filename' set but not used
(emitted by gcc)
variable 'filename' set but not used
(emitted by gcc)
variable 'filename' set but not used
(emitted by gcc)
795 796 /* Tuple access macros */ 797 798 #ifndef Py_DEBUG 799 #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i)) 800 #else 801 #define GETITEM(v, i) PyTuple_GetItem((v), (i)) 802 #endif 803 804 #ifdef WITH_TSC 805 /* Use Pentium timestamp counter to mark certain events: 806 inst0 -- beginning of switch statement for opcode dispatch 807 inst1 -- end of switch statement (may be skipped) 808 loop0 -- the top of the mainloop 809 loop1 -- place where control returns again to top of mainloop 810 (may be skipped) 811 intr1 -- beginning of long interruption 812 intr2 -- end of long interruption 813 814 Many opcodes call out to helper C functions. In some cases, the 815 time in those functions should be counted towards the time for the 816 opcode, but not in all cases. For example, a CALL_FUNCTION opcode 817 calls another Python function; there's no point in charge all the 818 bytecode executed by the called function to the caller. 819 820 It's hard to make a useful judgement statically. In the presence 821 of operator overloading, it's impossible to tell if a call will 822 execute new Python code or not. 823 824 It's a case-by-case judgement. I'll use intr1 for the following 825 cases: 826 827 EXEC_STMT 828 IMPORT_STAR 829 IMPORT_FROM 830 CALL_FUNCTION (and friends) 831 832 */ 833 uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0; 834 int ticked = 0; 835 836 READ_TIMESTAMP(inst0); 837 READ_TIMESTAMP(inst1); 838 READ_TIMESTAMP(loop0); 839 READ_TIMESTAMP(loop1); 840 841 /* shut up the compiler */ 842 opcode = 0; 843 #endif 844 845 /* Code access macros */ 846 847 #define INSTR_OFFSET() ((int)(next_instr - first_instr)) 848 #define NEXTOP() (*next_instr++) 849 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) 850 #define PEEKARG() ((next_instr[2]<<8) + next_instr[1]) 851 #define JUMPTO(x) (next_instr = first_instr + (x)) 852 #define JUMPBY(x) (next_instr += (x)) 853 854 /* OpCode prediction macros 855 Some opcodes tend to come in pairs thus making it possible to 856 predict the second code when the first is run. For example, 857 GET_ITER is often followed by FOR_ITER. And FOR_ITER is often 858 followed by STORE_FAST or UNPACK_SEQUENCE. 859 860 Verifying the prediction costs a single high-speed test of a register 861 variable against a constant. If the pairing was good, then the 862 processor's own internal branch predication has a high likelihood of 863 success, resulting in a nearly zero-overhead transition to the 864 next opcode. A successful prediction saves a trip through the eval-loop 865 including its two unpredictable branches, the HAS_ARG test and the 866 switch-case. Combined with the processor's internal branch prediction, 867 a successful PREDICT has the effect of making the two opcodes run as if 868 they were a single new opcode with the bodies combined. 869 870 If collecting opcode statistics, your choices are to either keep the 871 predictions turned-on and interpret the results as if some opcodes 872 had been combined or turn-off predictions so that the opcode frequency 873 counter updates for both opcodes. 874 */ 875 876 #ifdef DYNAMIC_EXECUTION_PROFILE 877 #define PREDICT(op) if (0) goto PRED_##op 878 #else 879 #define PREDICT(op) if (*next_instr == op) goto PRED_##op 880 #endif 881 882 #define PREDICTED(op) PRED_##op: next_instr++ 883 #define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3 884 885 /* Stack manipulation macros */ 886 887 /* The stack can grow at most MAXINT deep, as co_nlocals and 888 co_stacksize are ints. */ 889 #define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack)) 890 #define EMPTY() (STACK_LEVEL() == 0) 891 #define TOP() (stack_pointer[-1]) 892 #define SECOND() (stack_pointer[-2]) 893 #define THIRD() (stack_pointer[-3]) 894 #define FOURTH() (stack_pointer[-4]) 895 #define PEEK(n) (stack_pointer[-(n)]) 896 #define SET_TOP(v) (stack_pointer[-1] = (v)) 897 #define SET_SECOND(v) (stack_pointer[-2] = (v)) 898 #define SET_THIRD(v) (stack_pointer[-3] = (v)) 899 #define SET_FOURTH(v) (stack_pointer[-4] = (v)) 900 #define SET_VALUE(n, v) (stack_pointer[-(n)] = (v)) 901 #define BASIC_STACKADJ(n) (stack_pointer += n) 902 #define BASIC_PUSH(v) (*stack_pointer++ = (v)) 903 #define BASIC_POP() (*--stack_pointer) 904 905 #ifdef LLTRACE 906 #define PUSH(v) { (void)(BASIC_PUSH(v), \ 907 lltrace && prtrace(TOP(), "push")); \ 908 assert(STACK_LEVEL() <= co->co_stacksize); } 909 #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ 910 BASIC_POP()) 911 #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ 912 lltrace && prtrace(TOP(), "stackadj")); \ 913 assert(STACK_LEVEL() <= co->co_stacksize); } 914 #define EXT_POP(STACK_POINTER) ((void)(lltrace && \ 915 prtrace((STACK_POINTER)[-1], "ext_pop")), \ 916 *--(STACK_POINTER)) 917 #else 918 #define PUSH(v) BASIC_PUSH(v) 919 #define POP() BASIC_POP() 920 #define STACKADJ(n) BASIC_STACKADJ(n) 921 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER)) 922 #endif 923 924 /* Local variable macros */ 925 926 #define GETLOCAL(i) (fastlocals[i]) 927 928 /* The SETLOCAL() macro must not DECREF the local variable in-place and 929 then store the new value; it must copy the old value to a temporary 930 value, then store the new value, and then DECREF the temporary value. 931 This is because it is possible that during the DECREF the frame is 932 accessed by other code (e.g. a __del__ method or gc.collect()) and the 933 variable would be pointing to already-freed memory. */ 934 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ 935 GETLOCAL(i) = value; \ 936 Py_XDECREF(tmp); } while (0) 937 938 /* Start of code */ 939 940 if (f == NULL) 941 return NULL; 942 943 /* push frame */ 944 if (Py_EnterRecursiveCall("")) 945 return NULL; 946 947 tstate->frame = f; 948 949 if (tstate->use_tracing) { 950 if (tstate->c_tracefunc != NULL) { 951 /* tstate->c_tracefunc, if defined, is a 952 function that will be called on *every* entry 953 to a code block. Its return value, if not 954 None, is a function that will be called at 955 the start of each executed line of code. 956 (Actually, the function must return itself 957 in order to continue tracing.) The trace 958 functions are called with three arguments: 959 a pointer to the current frame, a string 960 indicating why the function is called, and 961 an argument which depends on the situation. 962 The global trace function is also called 963 whenever an exception is detected. */ 964 if (call_trace_protected(tstate->c_tracefunc, 965 tstate->c_traceobj, 966 f, PyTrace_CALL, Py_None)) { 967 /* Trace function raised an error */ 968 goto exit_eval_frame; 969 } 970 } 971 if (tstate->c_profilefunc != NULL) { 972 /* Similar for c_profilefunc, except it needn't 973 return itself and isn't called for "line" events */ 974 if (call_trace_protected(tstate->c_profilefunc, 975 tstate->c_profileobj, 976 f, PyTrace_CALL, Py_None)) { 977 /* Profile function raised an error */ 978 goto exit_eval_frame; 979 } 980 } 981 } 982 983 if (PYTHON_FUNCTION_ENTRY_ENABLED()) 984 dtrace_entry(f); 985 986 co = f->f_code; 987 names = co->co_names; 988 consts = co->co_consts; 989 fastlocals = f->f_localsplus; 990 freevars = f->f_localsplus + co->co_nlocals; 991 first_instr = (unsigned char*) PyString_AS_STRING(co->co_code); 992 /* An explanation is in order for the next line. 993 994 f->f_lasti now refers to the index of the last instruction 995 executed. You might think this was obvious from the name, but 996 this wasn't always true before 2.3! PyFrame_New now sets 997 f->f_lasti to -1 (i.e. the index *before* the first instruction) 998 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this 999 does work. Promise. 1000 1001 When the PREDICT() macros are enabled, some opcode pairs follow in 1002 direct succession without updating f->f_lasti. A successful 1003 prediction effectively links the two codes together as if they 1004 were a single new opcode; accordingly,f->f_lasti will point to 1005 the first code in the pair (for instance, GET_ITER followed by 1006 FOR_ITER is effectively a single opcode and f->f_lasti will point 1007 at to the beginning of the combined pair.) 1008 */ 1009 next_instr = first_instr + f->f_lasti + 1; 1010 stack_pointer = f->f_stacktop; 1011 assert(stack_pointer != NULL); 1012 f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */ 1013 1014 #ifdef LLTRACE 1015 lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL; 1016 #endif 1017 #if defined(Py_DEBUG) || defined(LLTRACE) 1018 filename = PyString_AsString(co->co_filename); 1019 #endif
Value stored to 'filename' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'filename' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'filename' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'filename' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

1020 1021 why = WHY_NOT; 1022 err = 0; 1023 x = Py_None; /* Not a reference, just anything non-NULL */ 1024 w = NULL; 1025 1026 if (throwflag) { /* support for generator.throw() */ 1027 why = WHY_EXCEPTION; 1028 goto on_error; 1029 } 1030 1031 for (;;) { 1032 #ifdef WITH_TSC 1033 if (inst1 == 0) { 1034 /* Almost surely, the opcode executed a break 1035 or a continue, preventing inst1 from being set 1036 on the way out of the loop. 1037 */ 1038 READ_TIMESTAMP(inst1); 1039 loop1 = inst1; 1040 } 1041 dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1, 1042 intr0, intr1); 1043 ticked = 0; 1044 inst1 = 0; 1045 intr0 = 0; 1046 intr1 = 0; 1047 READ_TIMESTAMP(loop0); 1048 #endif 1049 assert(stack_pointer >= f->f_valuestack); /* else underflow */ 1050 assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ 1051 1052 /* Do periodic things. Doing this every time through 1053 the loop would add too much overhead, so we do it 1054 only every Nth instruction. We also do it if 1055 ``pendingcalls_to_do'' is set, i.e. when an asynchronous 1056 event needs attention (e.g. a signal handler or 1057 async I/O handler); see Py_AddPendingCall() and 1058 Py_MakePendingCalls() above. */ 1059 1060 if (--_Py_Ticker < 0) { 1061 if (*next_instr == SETUP_FINALLY) { 1062 /* Make the last opcode before 1063 a try: finally: block uninterruptible. */ 1064 goto fast_next_opcode; 1065 } 1066 _Py_Ticker = _Py_CheckInterval; 1067 tstate->tick_counter++; 1068 #ifdef WITH_TSC 1069 ticked = 1; 1070 #endif 1071 if (pendingcalls_to_do) { 1072 if (Py_MakePendingCalls() < 0) { 1073 why = WHY_EXCEPTION; 1074 goto on_error; 1075 } 1076 if (pendingcalls_to_do) 1077 /* MakePendingCalls() didn't succeed. 1078 Force early re-execution of this 1079 "periodic" code, possibly after 1080 a thread switch */ 1081 _Py_Ticker = 0; 1082 } 1083 #ifdef WITH_THREAD 1084 if (interpreter_lock) { 1085 /* Give another thread a chance */ 1086 1087 if (PyThreadState_Swap(NULL) != tstate) 1088 Py_FatalError("ceval: tstate mix-up"); 1089 PyThread_release_lock(interpreter_lock); 1090 1091 /* Other threads may run now */ 1092 1093 PyThread_acquire_lock(interpreter_lock, 1); 1094 if (PyThreadState_Swap(tstate) != NULL) 1095 Py_FatalError("ceval: orphan tstate"); 1096 1097 /* Check for thread interrupts */ 1098 1099 if (tstate->async_exc != NULL) { 1100 x = tstate->async_exc; 1101 tstate->async_exc = NULL; 1102 PyErr_SetNone(x); 1103 Py_DECREF(x); 1104 why = WHY_EXCEPTION; 1105 goto on_error; 1106 } 1107 } 1108 #endif 1109 } 1110 1111 fast_next_opcode: 1112 f->f_lasti = INSTR_OFFSET(); 1113 1114 /* line-by-line tracing support */ 1115 1116 if (_Py_TracingPossible && 1117 tstate->c_tracefunc != NULL && !tstate->tracing) { 1118 /* see maybe_call_line_trace 1119 for expository comments */ 1120 f->f_stacktop = stack_pointer; 1121 1122 err = maybe_call_line_trace(tstate->c_tracefunc, 1123 tstate->c_traceobj, 1124 f, &instr_lb, &instr_ub, 1125 &instr_prev); 1126 /* Reload possibly changed frame fields */ 1127 JUMPTO(f->f_lasti); 1128 if (f->f_stacktop != NULL) { 1129 stack_pointer = f->f_stacktop; 1130 f->f_stacktop = NULL; 1131 } 1132 if (err) { 1133 /* trace function raised an exception */ 1134 goto on_error; 1135 } 1136 } 1137 1138 /* Extract opcode and argument */ 1139 1140 opcode = NEXTOP(); 1141 oparg = 0; /* allows oparg to be stored in a register because 1142 it doesn't have to be remembered across a full loop */ 1143 if (HAS_ARG(opcode)) 1144 oparg = NEXTARG(); 1145 dispatch_opcode: 1146 #ifdef DYNAMIC_EXECUTION_PROFILE 1147 #ifdef DXPAIRS 1148 dxpairs[lastopcode][opcode]++; 1149 lastopcode = opcode; 1150 #endif 1151 dxp[opcode]++; 1152 #endif 1153 1154 #ifdef LLTRACE 1155 /* Instruction tracing */ 1156 1157 if (lltrace) { 1158 if (HAS_ARG(opcode)) { 1159 printf("%d: %d, %d\n", 1160 f->f_lasti, opcode, oparg); 1161 } 1162 else { 1163 printf("%d: %d\n", 1164 f->f_lasti, opcode); 1165 } 1166 } 1167 #endif 1168 1169 /* Main switch on opcode */ 1170 READ_TIMESTAMP(inst0); 1171 1172 switch (opcode) { 1173 1174 /* BEWARE! 1175 It is essential that any operation that fails sets either 1176 x to NULL, err to nonzero, or why to anything but WHY_NOT, 1177 and that no operation that succeeds does this! */ 1178 1179 /* case STOP_CODE: this is an error! */ 1180 1181 case NOP: 1182 goto fast_next_opcode; 1183 1184 case LOAD_FAST: 1185 x = GETLOCAL(oparg); 1186 if (x != NULL) { 1187 Py_INCREF(x); 1188 PUSH(x); 1189 goto fast_next_opcode; 1190 } 1191 format_exc_check_arg(PyExc_UnboundLocalError, 1192 UNBOUNDLOCAL_ERROR_MSG, 1193 PyTuple_GetItem(co->co_varnames, oparg)); 1194 break; 1195 1196 case LOAD_CONST: 1197 x = GETITEM(consts, oparg); 1198 Py_INCREF(x); 1199 PUSH(x); 1200 goto fast_next_opcode; 1201 1202 PREDICTED_WITH_ARG(STORE_FAST); 1203 case STORE_FAST: 1204 v = POP(); 1205 SETLOCAL(oparg, v); 1206 goto fast_next_opcode; 1207 1208 case POP_TOP: 1209 v = POP(); 1210 Py_DECREF(v); 1211 goto fast_next_opcode; 1212 1213 case ROT_TWO: 1214 v = TOP(); 1215 w = SECOND(); 1216 SET_TOP(w); 1217 SET_SECOND(v); 1218 goto fast_next_opcode; 1219 1220 case ROT_THREE: 1221 v = TOP(); 1222 w = SECOND(); 1223 x = THIRD(); 1224 SET_TOP(w); 1225 SET_SECOND(x); 1226 SET_THIRD(v); 1227 goto fast_next_opcode; 1228 1229 case ROT_FOUR: 1230 u = TOP(); 1231 v = SECOND(); 1232 w = THIRD(); 1233 x = FOURTH(); 1234 SET_TOP(v); 1235 SET_SECOND(w); 1236 SET_THIRD(x); 1237 SET_FOURTH(u); 1238 goto fast_next_opcode; 1239 1240 case DUP_TOP: 1241 v = TOP(); 1242 Py_INCREF(v); 1243 PUSH(v); 1244 goto fast_next_opcode; 1245 1246 case DUP_TOPX: 1247 if (oparg == 2) { 1248 x = TOP(); 1249 Py_INCREF(x); 1250 w = SECOND(); 1251 Py_INCREF(w); 1252 STACKADJ(2); 1253 SET_TOP(x); 1254 SET_SECOND(w); 1255 goto fast_next_opcode; 1256 } else if (oparg == 3) { 1257 x = TOP(); 1258 Py_INCREF(x); 1259 w = SECOND(); 1260 Py_INCREF(w); 1261 v = THIRD(); 1262 Py_INCREF(v); 1263 STACKADJ(3); 1264 SET_TOP(x); 1265 SET_SECOND(w); 1266 SET_THIRD(v); 1267 goto fast_next_opcode; 1268 } 1269 Py_FatalError("invalid argument to DUP_TOPX" 1270 " (bytecode corruption?)"); 1271 /* Never returns, so don't bother to set why. */ 1272 break; 1273 1274 case UNARY_POSITIVE: 1275 v = TOP(); 1276 x = PyNumber_Positive(v); 1277 Py_DECREF(v); 1278 SET_TOP(x); 1279 if (x != NULL) continue; 1280 break; 1281 1282 case UNARY_NEGATIVE: 1283 v = TOP(); 1284 x = PyNumber_Negative(v); 1285 Py_DECREF(v); 1286 SET_TOP(x); 1287 if (x != NULL) continue; 1288 break; 1289 1290 case UNARY_NOT: 1291 v = TOP(); 1292 err = PyObject_IsTrue(v); 1293 Py_DECREF(v); 1294 if (err == 0) { 1295 Py_INCREF(Py_True); 1296 SET_TOP(Py_True); 1297 continue; 1298 } 1299 else if (err > 0) { 1300 Py_INCREF(Py_False); 1301 SET_TOP(Py_False); 1302 err = 0; 1303 continue; 1304 } 1305 STACKADJ(-1); 1306 break; 1307 1308 case UNARY_CONVERT: 1309 v = TOP(); 1310 x = PyObject_Repr(v); 1311 Py_DECREF(v); 1312 SET_TOP(x); 1313 if (x != NULL) continue; 1314 break; 1315 1316 case UNARY_INVERT: 1317 v = TOP(); 1318 x = PyNumber_Invert(v); 1319 Py_DECREF(v); 1320 SET_TOP(x); 1321 if (x != NULL) continue; 1322 break; 1323 1324 case BINARY_POWER: 1325 w = POP(); 1326 v = TOP(); 1327 x = PyNumber_Power(v, w, Py_None); 1328 Py_DECREF(v); 1329 Py_DECREF(w); 1330 SET_TOP(x); 1331 if (x != NULL) continue; 1332 break; 1333 1334 case BINARY_MULTIPLY: 1335 w = POP(); 1336 v = TOP(); 1337 x = PyNumber_Multiply(v, w); 1338 Py_DECREF(v); 1339 Py_DECREF(w); 1340 SET_TOP(x); 1341 if (x != NULL) continue; 1342 break; 1343 1344 case BINARY_DIVIDE: 1345 if (!_Py_QnewFlag) { 1346 w = POP(); 1347 v = TOP(); 1348 x = PyNumber_Divide(v, w); 1349 Py_DECREF(v); 1350 Py_DECREF(w); 1351 SET_TOP(x); 1352 if (x != NULL) continue; 1353 break; 1354 } 1355 /* -Qnew is in effect: fall through to 1356 BINARY_TRUE_DIVIDE */ 1357 case BINARY_TRUE_DIVIDE: 1358 w = POP(); 1359 v = TOP(); 1360 x = PyNumber_TrueDivide(v, w); 1361 Py_DECREF(v); 1362 Py_DECREF(w); 1363 SET_TOP(x); 1364 if (x != NULL) continue; 1365 break; 1366 1367 case BINARY_FLOOR_DIVIDE: 1368 w = POP(); 1369 v = TOP(); 1370 x = PyNumber_FloorDivide(v, w); 1371 Py_DECREF(v); 1372 Py_DECREF(w); 1373 SET_TOP(x); 1374 if (x != NULL) continue; 1375 break; 1376 1377 case BINARY_MODULO: 1378 w = POP(); 1379 v = TOP(); 1380 if (PyString_CheckExact(v)) 1381 x = PyString_Format(v, w); 1382 else 1383 x = PyNumber_Remainder(v, w); 1384 Py_DECREF(v); 1385 Py_DECREF(w); 1386 SET_TOP(x); 1387 if (x != NULL) continue; 1388 break; 1389 1390 case BINARY_ADD: 1391 w = POP(); 1392 v = TOP(); 1393 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { 1394 /* INLINE: int + int */ 1395 register long a, b, i; 1396 a = PyInt_AS_LONG(v); 1397 b = PyInt_AS_LONG(w); 1398 /* cast to avoid undefined behaviour 1399 on overflow */ 1400 i = (long)((unsigned long)a + b); 1401 if ((i^a) < 0 && (i^b) < 0) 1402 goto slow_add; 1403 x = PyInt_FromLong(i); 1404 } 1405 else if (PyString_CheckExact(v) && 1406 PyString_CheckExact(w)) { 1407 x = string_concatenate(v, w, f, next_instr); 1408 /* string_concatenate consumed the ref to v */ 1409 goto skip_decref_vx; 1410 } 1411 else { 1412 slow_add: 1413 x = PyNumber_Add(v, w); 1414 } 1415 Py_DECREF(v); 1416 skip_decref_vx: 1417 Py_DECREF(w); 1418 SET_TOP(x); 1419 if (x != NULL) continue; 1420 break; 1421 1422 case BINARY_SUBTRACT: 1423 w = POP(); 1424 v = TOP(); 1425 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { 1426 /* INLINE: int - int */ 1427 register long a, b, i; 1428 a = PyInt_AS_LONG(v); 1429 b = PyInt_AS_LONG(w); 1430 /* cast to avoid undefined behaviour 1431 on overflow */ 1432 i = (long)((unsigned long)a - b); 1433 if ((i^a) < 0 && (i^~b) < 0) 1434 goto slow_sub; 1435 x = PyInt_FromLong(i); 1436 } 1437 else { 1438 slow_sub: 1439 x = PyNumber_Subtract(v, w); 1440 } 1441 Py_DECREF(v); 1442 Py_DECREF(w); 1443 SET_TOP(x); 1444 if (x != NULL) continue; 1445 break; 1446 1447 case BINARY_SUBSCR: 1448 w = POP(); 1449 v = TOP(); 1450 if (PyList_CheckExact(v) && PyInt_CheckExact(w)) { 1451 /* INLINE: list[int] */ 1452 Py_ssize_t i = PyInt_AsSsize_t(w); 1453 if (i < 0) 1454 i += PyList_GET_SIZE(v); 1455 if (i >= 0 && i < PyList_GET_SIZE(v)) { 1456 x = PyList_GET_ITEM(v, i); 1457 Py_INCREF(x); 1458 } 1459 else 1460 goto slow_get; 1461 } 1462 else 1463 slow_get: 1464 x = PyObject_GetItem(v, w); 1465 Py_DECREF(v); 1466 Py_DECREF(w); 1467 SET_TOP(x); 1468 if (x != NULL) continue; 1469 break; 1470 1471 case BINARY_LSHIFT: 1472 w = POP(); 1473 v = TOP(); 1474 x = PyNumber_Lshift(v, w); 1475 Py_DECREF(v); 1476 Py_DECREF(w); 1477 SET_TOP(x); 1478 if (x != NULL) continue; 1479 break; 1480 1481 case BINARY_RSHIFT: 1482 w = POP(); 1483 v = TOP(); 1484 x = PyNumber_Rshift(v, w); 1485 Py_DECREF(v); 1486 Py_DECREF(w); 1487 SET_TOP(x); 1488 if (x != NULL) continue; 1489 break; 1490 1491 case BINARY_AND: 1492 w = POP(); 1493 v = TOP(); 1494 x = PyNumber_And(v, w); 1495 Py_DECREF(v); 1496 Py_DECREF(w); 1497 SET_TOP(x); 1498 if (x != NULL) continue; 1499 break; 1500 1501 case BINARY_XOR: 1502 w = POP(); 1503 v = TOP(); 1504 x = PyNumber_Xor(v, w); 1505 Py_DECREF(v); 1506 Py_DECREF(w); 1507 SET_TOP(x); 1508 if (x != NULL) continue; 1509 break; 1510 1511 case BINARY_OR: 1512 w = POP(); 1513 v = TOP(); 1514 x = PyNumber_Or(v, w); 1515 Py_DECREF(v); 1516 Py_DECREF(w); 1517 SET_TOP(x); 1518 if (x != NULL) continue; 1519 break; 1520 1521 case LIST_APPEND: 1522 w = POP(); 1523 v = PEEK(oparg); 1524 err = PyList_Append(v, w); 1525 Py_DECREF(w); 1526 if (err == 0) { 1527 PREDICT(JUMP_ABSOLUTE); 1528 continue; 1529 } 1530 break; 1531 1532 case SET_ADD: 1533 w = POP(); 1534 v = stack_pointer[-oparg]; 1535 err = PySet_Add(v, w); 1536 Py_DECREF(w); 1537 if (err == 0) { 1538 PREDICT(JUMP_ABSOLUTE); 1539 continue; 1540 } 1541 break; 1542 1543 case INPLACE_POWER: 1544 w = POP(); 1545 v = TOP(); 1546 x = PyNumber_InPlacePower(v, w, Py_None); 1547 Py_DECREF(v); 1548 Py_DECREF(w); 1549 SET_TOP(x); 1550 if (x != NULL) continue; 1551 break; 1552 1553 case INPLACE_MULTIPLY: 1554 w = POP(); 1555 v = TOP(); 1556 x = PyNumber_InPlaceMultiply(v, w); 1557 Py_DECREF(v); 1558 Py_DECREF(w); 1559 SET_TOP(x); 1560 if (x != NULL) continue; 1561 break; 1562 1563 case INPLACE_DIVIDE: 1564 if (!_Py_QnewFlag) { 1565 w = POP(); 1566 v = TOP(); 1567 x = PyNumber_InPlaceDivide(v, w); 1568 Py_DECREF(v); 1569 Py_DECREF(w); 1570 SET_TOP(x); 1571 if (x != NULL) continue; 1572 break; 1573 } 1574 /* -Qnew is in effect: fall through to 1575 INPLACE_TRUE_DIVIDE */ 1576 case INPLACE_TRUE_DIVIDE: 1577 w = POP(); 1578 v = TOP(); 1579 x = PyNumber_InPlaceTrueDivide(v, w); 1580 Py_DECREF(v); 1581 Py_DECREF(w); 1582 SET_TOP(x); 1583 if (x != NULL) continue; 1584 break; 1585 1586 case INPLACE_FLOOR_DIVIDE: 1587 w = POP(); 1588 v = TOP(); 1589 x = PyNumber_InPlaceFloorDivide(v, w); 1590 Py_DECREF(v); 1591 Py_DECREF(w); 1592 SET_TOP(x); 1593 if (x != NULL) continue; 1594 break; 1595 1596 case INPLACE_MODULO: 1597 w = POP(); 1598 v = TOP(); 1599 x = PyNumber_InPlaceRemainder(v, w); 1600 Py_DECREF(v); 1601 Py_DECREF(w); 1602 SET_TOP(x); 1603 if (x != NULL) continue; 1604 break; 1605 1606 case INPLACE_ADD: 1607 w = POP(); 1608 v = TOP(); 1609 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { 1610 /* INLINE: int + int */ 1611 register long a, b, i; 1612 a = PyInt_AS_LONG(v); 1613 b = PyInt_AS_LONG(w); 1614 i = a + b; 1615 if ((i^a) < 0 && (i^b) < 0) 1616 goto slow_iadd; 1617 x = PyInt_FromLong(i); 1618 } 1619 else if (PyString_CheckExact(v) && 1620 PyString_CheckExact(w)) { 1621 x = string_concatenate(v, w, f, next_instr); 1622 /* string_concatenate consumed the ref to v */ 1623 goto skip_decref_v; 1624 } 1625 else { 1626 slow_iadd: 1627 x = PyNumber_InPlaceAdd(v, w); 1628 } 1629 Py_DECREF(v); 1630 skip_decref_v: 1631 Py_DECREF(w); 1632 SET_TOP(x); 1633 if (x != NULL) continue; 1634 break; 1635 1636 case INPLACE_SUBTRACT: 1637 w = POP(); 1638 v = TOP(); 1639 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { 1640 /* INLINE: int - int */ 1641 register long a, b, i; 1642 a = PyInt_AS_LONG(v); 1643 b = PyInt_AS_LONG(w); 1644 i = a - b; 1645 if ((i^a) < 0 && (i^~b) < 0) 1646 goto slow_isub; 1647 x = PyInt_FromLong(i); 1648 } 1649 else { 1650 slow_isub: 1651 x = PyNumber_InPlaceSubtract(v, w); 1652 } 1653 Py_DECREF(v); 1654 Py_DECREF(w); 1655 SET_TOP(x); 1656 if (x != NULL) continue; 1657 break; 1658 1659 case INPLACE_LSHIFT: 1660 w = POP(); 1661 v = TOP(); 1662 x = PyNumber_InPlaceLshift(v, w); 1663 Py_DECREF(v); 1664 Py_DECREF(w); 1665 SET_TOP(x); 1666 if (x != NULL) continue; 1667 break; 1668 1669 case INPLACE_RSHIFT: 1670 w = POP(); 1671 v = TOP(); 1672 x = PyNumber_InPlaceRshift(v, w); 1673 Py_DECREF(v); 1674 Py_DECREF(w); 1675 SET_TOP(x); 1676 if (x != NULL) continue; 1677 break; 1678 1679 case INPLACE_AND: 1680 w = POP(); 1681 v = TOP(); 1682 x = PyNumber_InPlaceAnd(v, w); 1683 Py_DECREF(v); 1684 Py_DECREF(w); 1685 SET_TOP(x); 1686 if (x != NULL) continue; 1687 break; 1688 1689 case INPLACE_XOR: 1690 w = POP(); 1691 v = TOP(); 1692 x = PyNumber_InPlaceXor(v, w); 1693 Py_DECREF(v); 1694 Py_DECREF(w); 1695 SET_TOP(x); 1696 if (x != NULL) continue; 1697 break; 1698 1699 case INPLACE_OR: 1700 w = POP(); 1701 v = TOP(); 1702 x = PyNumber_InPlaceOr(v, w); 1703 Py_DECREF(v); 1704 Py_DECREF(w); 1705 SET_TOP(x); 1706 if (x != NULL) continue; 1707 break; 1708 1709 case SLICE+0: 1710 case SLICE+1: 1711 case SLICE+2: 1712 case SLICE+3: 1713 if ((opcode-SLICE) & 2) 1714 w = POP(); 1715 else 1716 w = NULL; 1717 if ((opcode-SLICE) & 1) 1718 v = POP(); 1719 else 1720 v = NULL; 1721 u = TOP(); 1722 x = apply_slice(u, v, w); 1723 Py_DECREF(u); 1724 Py_XDECREF(v); 1725 Py_XDECREF(w); 1726 SET_TOP(x); 1727 if (x != NULL) continue; 1728 break; 1729 1730 case STORE_SLICE+0: 1731 case STORE_SLICE+1: 1732 case STORE_SLICE+2: 1733 case STORE_SLICE+3: 1734 if ((opcode-STORE_SLICE) & 2) 1735 w = POP(); 1736 else 1737 w = NULL; 1738 if ((opcode-STORE_SLICE) & 1) 1739 v = POP(); 1740 else 1741 v = NULL; 1742 u = POP(); 1743 t = POP(); 1744 err = assign_slice(u, v, w, t); /* u[v:w] = t */ 1745 Py_DECREF(t); 1746 Py_DECREF(u); 1747 Py_XDECREF(v); 1748 Py_XDECREF(w); 1749 if (err == 0) continue; 1750 break; 1751 1752 case DELETE_SLICE+0: 1753 case DELETE_SLICE+1: 1754 case DELETE_SLICE+2: 1755 case DELETE_SLICE+3: 1756 if ((opcode-DELETE_SLICE) & 2) 1757 w = POP(); 1758 else 1759 w = NULL; 1760 if ((opcode-DELETE_SLICE) & 1) 1761 v = POP(); 1762 else 1763 v = NULL; 1764 u = POP(); 1765 err = assign_slice(u, v, w, (PyObject *)NULL); 1766 /* del u[v:w] */ 1767 Py_DECREF(u); 1768 Py_XDECREF(v); 1769 Py_XDECREF(w); 1770 if (err == 0) continue; 1771 break; 1772 1773 case STORE_SUBSCR: 1774 w = TOP(); 1775 v = SECOND(); 1776 u = THIRD(); 1777 STACKADJ(-3); 1778 /* v[w] = u */ 1779 err = PyObject_SetItem(v, w, u); 1780 Py_DECREF(u); 1781 Py_DECREF(v); 1782 Py_DECREF(w); 1783 if (err == 0) continue; 1784 break; 1785 1786 case DELETE_SUBSCR: 1787 w = TOP(); 1788 v = SECOND(); 1789 STACKADJ(-2); 1790 /* del v[w] */ 1791 err = PyObject_DelItem(v, w); 1792 Py_DECREF(v); 1793 Py_DECREF(w); 1794 if (err == 0) continue; 1795 break; 1796 1797 case PRINT_EXPR: 1798 v = POP(); 1799 w = PySys_GetObject("displayhook"); 1800 if (w == NULL) { 1801 PyErr_SetString(PyExc_RuntimeError, 1802 "lost sys.displayhook"); 1803 err = -1; 1804 x = NULL; 1805 } 1806 if (err == 0) { 1807 x = PyTuple_Pack(1, v); 1808 if (x == NULL) 1809 err = -1; 1810 } 1811 if (err == 0) { 1812 w = PyEval_CallObject(w, x); 1813 Py_XDECREF(w); 1814 if (w == NULL) 1815 err = -1; 1816 } 1817 Py_DECREF(v); 1818 Py_XDECREF(x); 1819 break; 1820 1821 case PRINT_ITEM_TO: 1822 w = stream = POP(); 1823 /* fall through to PRINT_ITEM */ 1824 1825 case PRINT_ITEM: 1826 v = POP(); 1827 if (stream == NULL || stream == Py_None) { 1828 w = PySys_GetObject("stdout"); 1829 if (w == NULL) { 1830 PyErr_SetString(PyExc_RuntimeError, 1831 "lost sys.stdout"); 1832 err = -1; 1833 } 1834 } 1835 /* PyFile_SoftSpace() can exececute arbitrary code 1836 if sys.stdout is an instance with a __getattr__. 1837 If __getattr__ raises an exception, w will 1838 be freed, so we need to prevent that temporarily. */ 1839 Py_XINCREF(w); 1840 if (w != NULL && PyFile_SoftSpace(w, 0)) 1841 err = PyFile_WriteString(" ", w); 1842 if (err == 0) 1843 err = PyFile_WriteObject(v, w, Py_PRINT_RAW); 1844 if (err == 0) { 1845 /* XXX move into writeobject() ? */ 1846 if (PyString_Check(v)) { 1847 char *s = PyString_AS_STRING(v); 1848 Py_ssize_t len = PyString_GET_SIZE(v); 1849 if (len == 0 || 1850 !isspace(Py_CHARMASK(s[len-1])) || 1851 s[len-1] == ' ') 1852 PyFile_SoftSpace(w, 1); 1853 } 1854 #ifdef Py_USING_UNICODE 1855 else if (PyUnicode_Check(v)) { 1856 Py_UNICODE *s = PyUnicode_AS_UNICODE(v); 1857 Py_ssize_t len = PyUnicode_GET_SIZE(v); 1858 if (len == 0 || 1859 !Py_UNICODE_ISSPACE(s[len-1]) || 1860 s[len-1] == ' ') 1861 PyFile_SoftSpace(w, 1); 1862 } 1863 #endif 1864 else 1865 PyFile_SoftSpace(w, 1); 1866 } 1867 Py_XDECREF(w); 1868 Py_DECREF(v); 1869 Py_XDECREF(stream); 1870 stream = NULL; 1871 if (err == 0) 1872 continue; 1873 break; 1874 1875 case PRINT_NEWLINE_TO: 1876 w = stream = POP(); 1877 /* fall through to PRINT_NEWLINE */ 1878 1879 case PRINT_NEWLINE: 1880 if (stream == NULL || stream == Py_None) { 1881 w = PySys_GetObject("stdout"); 1882 if (w == NULL) { 1883 PyErr_SetString(PyExc_RuntimeError, 1884 "lost sys.stdout"); 1885 why = WHY_EXCEPTION; 1886 } 1887 } 1888 if (w != NULL) { 1889 /* w.write() may replace sys.stdout, so we 1890 * have to keep our reference to it */ 1891 Py_INCREF(w); 1892 err = PyFile_WriteString("\n", w); 1893 if (err == 0) 1894 PyFile_SoftSpace(w, 0); 1895 Py_DECREF(w); 1896 } 1897 Py_XDECREF(stream); 1898 stream = NULL; 1899 break; 1900 1901 1902 #ifdef CASE_TOO_BIG 1903 default: switch (opcode) { 1904 #endif 1905 case RAISE_VARARGS: 1906 u = v = w = NULL; 1907 switch (oparg) { 1908 case 3: 1909 u = POP(); /* traceback */ 1910 /* Fallthrough */ 1911 case 2: 1912 v = POP(); /* value */ 1913 /* Fallthrough */ 1914 case 1: 1915 w = POP(); /* exc */ 1916 case 0: /* Fallthrough */ 1917 why = do_raise(w, v, u); 1918 break; 1919 default: 1920 PyErr_SetString(PyExc_SystemError, 1921 "bad RAISE_VARARGS oparg"); 1922 why = WHY_EXCEPTION; 1923 break; 1924 } 1925 break; 1926 1927 case LOAD_LOCALS: 1928 if ((x = f->f_locals) != NULL) { 1929 Py_INCREF(x); 1930 PUSH(x); 1931 continue; 1932 } 1933 PyErr_SetString(PyExc_SystemError, "no locals"); 1934 break; 1935 1936 case RETURN_VALUE: 1937 retval = POP(); 1938 why = WHY_RETURN; 1939 goto fast_block_end; 1940 1941 case YIELD_VALUE: 1942 retval = POP(); 1943 f->f_stacktop = stack_pointer; 1944 why = WHY_YIELD; 1945 goto fast_yield; 1946 1947 case EXEC_STMT: 1948 w = TOP(); 1949 v = SECOND(); 1950 u = THIRD(); 1951 STACKADJ(-3); 1952 READ_TIMESTAMP(intr0); 1953 err = exec_statement(f, u, v, w); 1954 READ_TIMESTAMP(intr1); 1955 Py_DECREF(u); 1956 Py_DECREF(v); 1957 Py_DECREF(w); 1958 break; 1959 1960 case POP_BLOCK: 1961 { 1962 PyTryBlock *b = PyFrame_BlockPop(f); 1963 while (STACK_LEVEL() > b->b_level) { 1964 v = POP(); 1965 Py_DECREF(v); 1966 } 1967 } 1968 continue; 1969 1970 PREDICTED(END_FINALLY); 1971 case END_FINALLY: 1972 v = POP(); 1973 if (PyInt_Check(v)) { 1974 why = (enum why_code) PyInt_AS_LONG(v); 1975 assert(why != WHY_YIELD); 1976 if (why == WHY_RETURN || 1977 why == WHY_CONTINUE) 1978 retval = POP(); 1979 } 1980 else if (PyExceptionClass_Check(v) || 1981 PyString_Check(v)) { 1982 w = POP(); 1983 u = POP(); 1984 PyErr_Restore(v, w, u); 1985 why = WHY_RERAISE; 1986 break; 1987 } 1988 else if (v != Py_None) { 1989 PyErr_SetString(PyExc_SystemError, 1990 "'finally' pops bad exception"); 1991 why = WHY_EXCEPTION; 1992 } 1993 Py_DECREF(v); 1994 break; 1995 1996 case BUILD_CLASS: 1997 u = TOP(); 1998 v = SECOND(); 1999 w = THIRD(); 2000 STACKADJ(-2); 2001 x = build_class(u, v, w); 2002 SET_TOP(x); 2003 Py_DECREF(u); 2004 Py_DECREF(v); 2005 Py_DECREF(w); 2006 break; 2007 2008 case STORE_NAME: 2009 w = GETITEM(names, oparg); 2010 v = POP(); 2011 if ((x = f->f_locals) != NULL) { 2012 if (PyDict_CheckExact(x)) 2013 err = PyDict_SetItem(x, w, v); 2014 else 2015 err = PyObject_SetItem(x, w, v); 2016 Py_DECREF(v); 2017 if (err == 0) continue; 2018 break; 2019 } 2020 PyErr_Format(PyExc_SystemError, 2021 "no locals found when storing %s", 2022 PyObject_REPR(w)); 2023 break; 2024 2025 case DELETE_NAME: 2026 w = GETITEM(names, oparg); 2027 if ((x = f->f_locals) != NULL) { 2028 if ((err = PyObject_DelItem(x, w)) != 0) 2029 format_exc_check_arg(PyExc_NameError, 2030 NAME_ERROR_MSG, 2031 w); 2032 break; 2033 } 2034 PyErr_Format(PyExc_SystemError, 2035 "no locals when deleting %s", 2036 PyObject_REPR(w)); 2037 break; 2038 2039 PREDICTED_WITH_ARG(UNPACK_SEQUENCE); 2040 case UNPACK_SEQUENCE: 2041 v = POP(); 2042 if (PyTuple_CheckExact(v) && 2043 PyTuple_GET_SIZE(v) == oparg) { 2044 PyObject **items = \ 2045 ((PyTupleObject *)v)->ob_item; 2046 while (oparg--) { 2047 w = items[oparg]; 2048 Py_INCREF(w); 2049 PUSH(w); 2050 } 2051 Py_DECREF(v); 2052 continue; 2053 } else if (PyList_CheckExact(v) && 2054 PyList_GET_SIZE(v) == oparg) { 2055 PyObject **items = \ 2056 ((PyListObject *)v)->ob_item; 2057 while (oparg--) { 2058 w = items[oparg]; 2059 Py_INCREF(w); 2060 PUSH(w); 2061 } 2062 } else if (unpack_iterable(v, oparg, 2063 stack_pointer + oparg)) { 2064 STACKADJ(oparg); 2065 } else { 2066 /* unpack_iterable() raised an exception */ 2067 why = WHY_EXCEPTION; 2068 } 2069 Py_DECREF(v); 2070 break; 2071 2072 case STORE_ATTR: 2073 w = GETITEM(names, oparg); 2074 v = TOP(); 2075 u = SECOND(); 2076 STACKADJ(-2); 2077 err = PyObject_SetAttr(v, w, u); /* v.w = u */ 2078 Py_DECREF(v); 2079 Py_DECREF(u); 2080 if (err == 0) continue; 2081 break; 2082 2083 case DELETE_ATTR: 2084 w = GETITEM(names, oparg); 2085 v = POP(); 2086 err = PyObject_SetAttr(v, w, (PyObject *)NULL); 2087 /* del v.w */ 2088 Py_DECREF(v); 2089 break; 2090 2091 case STORE_GLOBAL: 2092 w = GETITEM(names, oparg); 2093 v = POP(); 2094 err = PyDict_SetItem(f->f_globals, w, v); 2095 Py_DECREF(v); 2096 if (err == 0) continue; 2097 break; 2098 2099 case DELETE_GLOBAL: 2100 w = GETITEM(names, oparg); 2101 if ((err = PyDict_DelItem(f->f_globals, w)) != 0) 2102 format_exc_check_arg( 2103 PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w); 2104 break; 2105 2106 case LOAD_NAME: 2107 w = GETITEM(names, oparg); 2108 if ((v = f->f_locals) == NULL) { 2109 PyErr_Format(PyExc_SystemError, 2110 "no locals when loading %s", 2111 PyObject_REPR(w)); 2112 why = WHY_EXCEPTION; 2113 break; 2114 } 2115 if (PyDict_CheckExact(v)) { 2116 x = PyDict_GetItem(v, w); 2117 Py_XINCREF(x); 2118 } 2119 else { 2120 x = PyObject_GetItem(v, w); 2121 if (x == NULL && PyErr_Occurred()) { 2122 if (!PyErr_ExceptionMatches( 2123 PyExc_KeyError)) 2124 break; 2125 PyErr_Clear(); 2126 } 2127 } 2128 if (x == NULL) { 2129 x = PyDict_GetItem(f->f_globals, w); 2130 if (x == NULL) { 2131 x = PyDict_GetItem(f->f_builtins, w); 2132 if (x == NULL) { 2133 format_exc_check_arg( 2134 PyExc_NameError, 2135 NAME_ERROR_MSG, w); 2136 break; 2137 } 2138 } 2139 Py_INCREF(x); 2140 } 2141 PUSH(x); 2142 continue; 2143 2144 case LOAD_GLOBAL: 2145 w = GETITEM(names, oparg); 2146 if (PyString_CheckExact(w)) { 2147 /* Inline the PyDict_GetItem() calls. 2148 WARNING: this is an extreme speed hack. 2149 Do not try this at home. */ 2150 long hash = ((PyStringObject *)w)->ob_shash; 2151 if (hash != -1) { 2152 PyDictObject *d; 2153 PyDictEntry *e; 2154 d = (PyDictObject *)(f->f_globals); 2155 e = d->ma_lookup(d, w, hash); 2156 if (e == NULL) { 2157 x = NULL; 2158 break; 2159 } 2160 x = e->me_value; 2161 if (x != NULL) { 2162 Py_INCREF(x); 2163 PUSH(x); 2164 continue; 2165 } 2166 d = (PyDictObject *)(f->f_builtins); 2167 e = d->ma_lookup(d, w, hash); 2168 if (e == NULL) { 2169 x = NULL; 2170 break; 2171 } 2172 x = e->me_value; 2173 if (x != NULL) { 2174 Py_INCREF(x); 2175 PUSH(x); 2176 continue; 2177 } 2178 goto load_global_error; 2179 } 2180 } 2181 /* This is the un-inlined version of the code above */ 2182 x = PyDict_GetItem(f->f_globals, w); 2183 if (x == NULL) { 2184 x = PyDict_GetItem(f->f_builtins, w); 2185 if (x == NULL) { 2186 load_global_error: 2187 format_exc_check_arg( 2188 PyExc_NameError, 2189 GLOBAL_NAME_ERROR_MSG, w); 2190 break; 2191 } 2192 } 2193 Py_INCREF(x); 2194 PUSH(x); 2195 continue; 2196 2197 case DELETE_FAST: 2198 x = GETLOCAL(oparg); 2199 if (x != NULL) { 2200 SETLOCAL(oparg, NULL); 2201 continue; 2202 } 2203 format_exc_check_arg( 2204 PyExc_UnboundLocalError, 2205 UNBOUNDLOCAL_ERROR_MSG, 2206 PyTuple_GetItem(co->co_varnames, oparg) 2207 ); 2208 break; 2209 2210 case LOAD_CLOSURE: 2211 x = freevars[oparg]; 2212 Py_INCREF(x); 2213 PUSH(x); 2214 if (x != NULL) continue; 2215 break; 2216 2217 case LOAD_DEREF: 2218 x = freevars[oparg]; 2219 w = PyCell_Get(x); 2220 if (w != NULL) { 2221 PUSH(w); 2222 continue; 2223 } 2224 err = -1; 2225 /* Don't stomp existing exception */ 2226 if (PyErr_Occurred()) 2227 break; 2228 if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { 2229 v = PyTuple_GET_ITEM(co->co_cellvars, 2230 oparg); 2231 format_exc_check_arg( 2232 PyExc_UnboundLocalError, 2233 UNBOUNDLOCAL_ERROR_MSG, 2234 v); 2235 } else { 2236 v = PyTuple_GET_ITEM(co->co_freevars, oparg - 2237 PyTuple_GET_SIZE(co->co_cellvars)); 2238 format_exc_check_arg(PyExc_NameError, 2239 UNBOUNDFREE_ERROR_MSG, v); 2240 } 2241 break; 2242 2243 case STORE_DEREF: 2244 w = POP(); 2245 x = freevars[oparg]; 2246 PyCell_Set(x, w); 2247 Py_DECREF(w); 2248 continue; 2249 2250 case BUILD_TUPLE: 2251 x = PyTuple_New(oparg); 2252 if (x != NULL) { 2253 for (; --oparg >= 0;) { 2254 w = POP(); 2255 PyTuple_SET_ITEM(x, oparg, w); 2256 } 2257 PUSH(x); 2258 continue; 2259 } 2260 break; 2261 2262 case BUILD_LIST: 2263 x = PyList_New(oparg); 2264 if (x != NULL) { 2265 for (; --oparg >= 0;) { 2266 w = POP(); 2267 PyList_SET_ITEM(x, oparg, w); 2268 } 2269 PUSH(x); 2270 continue; 2271 } 2272 break; 2273 2274 case BUILD_SET: 2275 x = PySet_New(NULL); 2276 if (x != NULL) { 2277 for (; --oparg >= 0;) { 2278 w = POP(); 2279 if (err == 0) 2280 err = PySet_Add(x, w); 2281 Py_DECREF(w); 2282 } 2283 if (err != 0) { 2284 Py_DECREF(x); 2285 break; 2286 } 2287 PUSH(x); 2288 continue; 2289 } 2290 break; 2291 2292 2293 case BUILD_MAP: 2294 x = _PyDict_NewPresized((Py_ssize_t)oparg); 2295 PUSH(x); 2296 if (x != NULL) continue; 2297 break; 2298 2299 case STORE_MAP: 2300 w = TOP(); /* key */ 2301 u = SECOND(); /* value */ 2302 v = THIRD(); /* dict */ 2303 STACKADJ(-2); 2304 assert (PyDict_CheckExact(v)); 2305 err = PyDict_SetItem(v, w, u); /* v[w] = u */ 2306 Py_DECREF(u); 2307 Py_DECREF(w); 2308 if (err == 0) continue; 2309 break; 2310 2311 case MAP_ADD: 2312 w = TOP(); /* key */ 2313 u = SECOND(); /* value */ 2314 STACKADJ(-2); 2315 v = stack_pointer[-oparg]; /* dict */ 2316 assert (PyDict_CheckExact(v)); 2317 err = PyDict_SetItem(v, w, u); /* v[w] = u */ 2318 Py_DECREF(u); 2319 Py_DECREF(w); 2320 if (err == 0) { 2321 PREDICT(JUMP_ABSOLUTE); 2322 continue; 2323 } 2324 break; 2325 2326 case LOAD_ATTR: 2327 w = GETITEM(names, oparg); 2328 v = TOP(); 2329 x = PyObject_GetAttr(v, w); 2330 Py_DECREF(v); 2331 SET_TOP(x); 2332 if (x != NULL) continue; 2333 break; 2334 2335 case COMPARE_OP: 2336 w = POP(); 2337 v = TOP(); 2338 if (PyInt_CheckExact(w) && PyInt_CheckExact(v)) { 2339 /* INLINE: cmp(int, int) */ 2340 register long a, b; 2341 register int res; 2342 a = PyInt_AS_LONG(v); 2343 b = PyInt_AS_LONG(w); 2344 switch (oparg) { 2345 case PyCmp_LT: res = a < b; break; 2346 case PyCmp_LE: res = a <= b; break; 2347 case PyCmp_EQ: res = a == b; break; 2348 case PyCmp_NE: res = a != b; break; 2349 case PyCmp_GT: res = a > b; break; 2350 case PyCmp_GE: res = a >= b; break; 2351 case PyCmp_IS: res = v == w; break; 2352 case PyCmp_IS_NOT: res = v != w; break; 2353 default: goto slow_compare; 2354 } 2355 x = res ? Py_True : Py_False; 2356 Py_INCREF(x); 2357 } 2358 else { 2359 slow_compare: 2360 x = cmp_outcome(oparg, v, w); 2361 } 2362 Py_DECREF(v); 2363 Py_DECREF(w); 2364 SET_TOP(x); 2365 if (x == NULL) break; 2366 PREDICT(POP_JUMP_IF_FALSE); 2367 PREDICT(POP_JUMP_IF_TRUE); 2368 continue; 2369 2370 case IMPORT_NAME: 2371 w = GETITEM(names, oparg); 2372 x = PyDict_GetItemString(f->f_builtins, "__import__"); 2373 if (x == NULL) { 2374 PyErr_SetString(PyExc_ImportError, 2375 "__import__ not found"); 2376 break; 2377 } 2378 Py_INCREF(x); 2379 v = POP(); 2380 u = TOP(); 2381 if (PyInt_AsLong(u) != -1 || PyErr_Occurred()) 2382 w = PyTuple_Pack(5, 2383 w, 2384 f->f_globals, 2385 f->f_locals == NULL ? 2386 Py_None : f->f_locals, 2387 v, 2388 u); 2389 else 2390 w = PyTuple_Pack(4, 2391 w, 2392 f->f_globals, 2393 f->f_locals == NULL ? 2394 Py_None : f->f_locals, 2395 v); 2396 Py_DECREF(v); 2397 Py_DECREF(u); 2398 if (w == NULL) { 2399 u = POP(); 2400 Py_DECREF(x);
Value stored to 'u' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'u' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'u' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'u' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'u' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'u' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'u' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'u' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

2401 x = NULL; 2402 break; 2403 } 2404 READ_TIMESTAMP(intr0); 2405 v = x; 2406 x = PyEval_CallObject(v, w); 2407 Py_DECREF(v); 2408 READ_TIMESTAMP(intr1); 2409 Py_DECREF(w); 2410 SET_TOP(x); 2411 if (x != NULL) continue; 2412 break; 2413 2414 case IMPORT_STAR: 2415 v = POP(); 2416 PyFrame_FastToLocals(f); 2417 if ((x = f->f_locals) == NULL) { 2418 PyErr_SetString(PyExc_SystemError, 2419 "no locals found during 'import *'"); 2420 break; 2421 } 2422 READ_TIMESTAMP(intr0); 2423 err = import_all_from(x, v); 2424 READ_TIMESTAMP(intr1); 2425 PyFrame_LocalsToFast(f, 0); 2426 Py_DECREF(v); 2427 if (err == 0) continue; 2428 break; 2429 2430 case IMPORT_FROM: 2431 w = GETITEM(names, oparg); 2432 v = TOP(); 2433 READ_TIMESTAMP(intr0); 2434 x = import_from(v, w); 2435 READ_TIMESTAMP(intr1); 2436 PUSH(x); 2437 if (x != NULL) continue; 2438 break; 2439 2440 case JUMP_FORWARD: 2441 JUMPBY(oparg); 2442 goto fast_next_opcode; 2443 2444 PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE); 2445 case POP_JUMP_IF_FALSE: 2446 w = POP(); 2447 if (w == Py_True) { 2448 Py_DECREF(w); 2449 goto fast_next_opcode; 2450 } 2451 if (w == Py_False) { 2452 Py_DECREF(w); 2453 JUMPTO(oparg); 2454 goto fast_next_opcode; 2455 } 2456 err = PyObject_IsTrue(w); 2457 Py_DECREF(w); 2458 if (err > 0) 2459 err = 0; 2460 else if (err == 0) 2461 JUMPTO(oparg); 2462 else 2463 break; 2464 continue; 2465 2466 PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE); 2467 case POP_JUMP_IF_TRUE: 2468 w = POP(); 2469 if (w == Py_False) { 2470 Py_DECREF(w); 2471 goto fast_next_opcode; 2472 } 2473 if (w == Py_True) { 2474 Py_DECREF(w); 2475 JUMPTO(oparg); 2476 goto fast_next_opcode; 2477 } 2478 err = PyObject_IsTrue(w); 2479 Py_DECREF(w); 2480 if (err > 0) { 2481 err = 0; 2482 JUMPTO(oparg); 2483 } 2484 else if (err == 0) 2485 ; 2486 else 2487 break; 2488 continue; 2489 2490 case JUMP_IF_FALSE_OR_POP: 2491 w = TOP(); 2492 if (w == Py_True) { 2493 STACKADJ(-1); 2494 Py_DECREF(w); 2495 goto fast_next_opcode; 2496 } 2497 if (w == Py_False) { 2498 JUMPTO(oparg); 2499 goto fast_next_opcode; 2500 } 2501 err = PyObject_IsTrue(w); 2502 if (err > 0) { 2503 STACKADJ(-1); 2504 Py_DECREF(w); 2505 err = 0; 2506 } 2507 else if (err == 0) 2508 JUMPTO(oparg); 2509 else 2510 break; 2511 continue; 2512 2513 case JUMP_IF_TRUE_OR_POP: 2514 w = TOP(); 2515 if (w == Py_False) { 2516 STACKADJ(-1); 2517 Py_DECREF(w); 2518 goto fast_next_opcode; 2519 } 2520 if (w == Py_True) { 2521 JUMPTO(oparg); 2522 goto fast_next_opcode; 2523 } 2524 err = PyObject_IsTrue(w); 2525 if (err > 0) { 2526 err = 0; 2527 JUMPTO(oparg); 2528 } 2529 else if (err == 0) { 2530 STACKADJ(-1); 2531 Py_DECREF(w); 2532 } 2533 else 2534 break; 2535 continue; 2536 2537 PREDICTED_WITH_ARG(JUMP_ABSOLUTE); 2538 case JUMP_ABSOLUTE: 2539 JUMPTO(oparg); 2540 #if FAST_LOOPS 2541 /* Enabling this path speeds-up all while and for-loops by bypassing 2542 the per-loop checks for signals. By default, this should be turned-off 2543 because it prevents detection of a control-break in tight loops like 2544 "while 1: pass". Compile with this option turned-on when you need 2545 the speed-up and do not need break checking inside tight loops (ones 2546 that contain only instructions ending with goto fast_next_opcode). 2547 */ 2548 goto fast_next_opcode; 2549 #else 2550 continue; 2551 #endif 2552 2553 case GET_ITER: 2554 /* before: [obj]; after [getiter(obj)] */ 2555 v = TOP(); 2556 x = PyObject_GetIter(v); 2557 Py_DECREF(v); 2558 if (x != NULL) { 2559 SET_TOP(x); 2560 PREDICT(FOR_ITER); 2561 continue; 2562 } 2563 STACKADJ(-1); 2564 break; 2565 2566 PREDICTED_WITH_ARG(FOR_ITER); 2567 case FOR_ITER: 2568 /* before: [iter]; after: [iter, iter()] *or* [] */ 2569 v = TOP(); 2570 x = (*v->ob_type->tp_iternext)(v); 2571 if (x != NULL) { 2572 PUSH(x); 2573 PREDICT(STORE_FAST); 2574 PREDICT(UNPACK_SEQUENCE); 2575 continue; 2576 } 2577 if (PyErr_Occurred()) { 2578 if (!PyErr_ExceptionMatches( 2579 PyExc_StopIteration)) 2580 break; 2581 PyErr_Clear(); 2582 } 2583 /* iterator ended normally */ 2584 x = v = POP(); 2585 Py_DECREF(v); 2586 JUMPBY(oparg); 2587 continue; 2588 2589 case BREAK_LOOP: 2590 why = WHY_BREAK; 2591 goto fast_block_end; 2592 2593 case CONTINUE_LOOP: 2594 retval = PyInt_FromLong(oparg); 2595 if (!retval) { 2596 x = NULL; 2597 break; 2598 } 2599 why = WHY_CONTINUE; 2600 goto fast_block_end; 2601 2602 case SETUP_LOOP: 2603 case SETUP_EXCEPT: 2604 case SETUP_FINALLY: 2605 /* NOTE: If you add any new block-setup opcodes that 2606 are not try/except/finally handlers, you may need 2607 to update the PyGen_NeedsFinalizing() function. 2608 */ 2609 2610 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, 2611 STACK_LEVEL()); 2612 continue; 2613 2614 case SETUP_WITH: 2615 { 2616 static PyObject *exit, *enter; 2617 w = TOP(); 2618 x = special_lookup(w, "__exit__", &exit); 2619 if (!x) 2620 break; 2621 SET_TOP(x); 2622 u = special_lookup(w, "__enter__", &enter); 2623 Py_DECREF(w); 2624 if (!u) { 2625 x = NULL; 2626 break; 2627 } 2628 x = PyObject_CallFunctionObjArgs(u, NULL); 2629 Py_DECREF(u); 2630 if (!x) 2631 break; 2632 /* Setup a finally block (SETUP_WITH as a block is 2633 equivalent to SETUP_FINALLY except it normalizes 2634 the exception) before pushing the result of 2635 __enter__ on the stack. */ 2636 PyFrame_BlockSetup(f, SETUP_WITH, INSTR_OFFSET() + oparg, 2637 STACK_LEVEL()); 2638 2639 PUSH(x); 2640 continue; 2641 } 2642 2643 case WITH_CLEANUP: 2644 { 2645 /* At the top of the stack are 1-3 values indicating 2646 how/why we entered the finally clause: 2647 - TOP = None 2648 - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval 2649 - TOP = WHY_*; no retval below it 2650 - (TOP, SECOND, THIRD) = exc_info() 2651 Below them is EXIT, the context.__exit__ bound method. 2652 In the last case, we must call 2653 EXIT(TOP, SECOND, THIRD) 2654 otherwise we must call 2655 EXIT(None, None, None) 2656 2657 In all cases, we remove EXIT from the stack, leaving 2658 the rest in the same order. 2659 2660 In addition, if the stack represents an exception, 2661 *and* the function call returns a 'true' value, we 2662 "zap" this information, to prevent END_FINALLY from 2663 re-raising the exception. (But non-local gotos 2664 should still be resumed.) 2665 */ 2666 2667 PyObject *exit_func; 2668 2669 u = POP(); 2670 if (u == Py_None) { 2671 exit_func = TOP(); 2672 SET_TOP(u); 2673 v = w = Py_None; 2674 } 2675 else if (PyInt_Check(u)) { 2676 switch(PyInt_AS_LONG(u)) { 2677 case WHY_RETURN: 2678 case WHY_CONTINUE: 2679 /* Retval in TOP. */ 2680 exit_func = SECOND(); 2681 SET_SECOND(TOP()); 2682 SET_TOP(u); 2683 break; 2684 default: 2685 exit_func = TOP(); 2686 SET_TOP(u); 2687 break; 2688 } 2689 u = v = w = Py_None; 2690 } 2691 else { 2692 v = TOP(); 2693 w = SECOND(); 2694 exit_func = THIRD(); 2695 SET_TOP(u); 2696 SET_SECOND(v); 2697 SET_THIRD(w); 2698 } 2699 /* XXX Not the fastest way to call it... */ 2700 x = PyObject_CallFunctionObjArgs(exit_func, u, v, w, 2701 NULL); 2702 Py_DECREF(exit_func); 2703 if (x == NULL) 2704 break; /* Go to error exit */ 2705 2706 if (u != Py_None) 2707 err = PyObject_IsTrue(x); 2708 else 2709 err = 0; 2710 Py_DECREF(x); 2711 2712 if (err < 0) 2713 break; /* Go to error exit */ 2714 else if (err > 0) { 2715 err = 0; 2716 /* There was an exception and a true return */ 2717 STACKADJ(-2); 2718 Py_INCREF(Py_None); 2719 SET_TOP(Py_None); 2720 Py_DECREF(u); 2721 Py_DECREF(v); 2722 Py_DECREF(w); 2723 } else { 2724 /* The stack was rearranged to remove EXIT 2725 above. Let END_FINALLY do its thing */ 2726 } 2727 PREDICT(END_FINALLY); 2728 break; 2729 } 2730 2731 case CALL_FUNCTION: 2732 { 2733 PyObject **sp; 2734 PCALL(PCALL_ALL); 2735 sp = stack_pointer; 2736 #ifdef WITH_TSC 2737 x = call_function(&sp, oparg, &intr0, &intr1); 2738 #else 2739 x = call_function(&sp, oparg); 2740 #endif 2741 stack_pointer = sp; 2742 PUSH(x); 2743 if (x != NULL) 2744 continue; 2745 break; 2746 } 2747 2748 case CALL_FUNCTION_VAR: 2749 case CALL_FUNCTION_KW: 2750 case CALL_FUNCTION_VAR_KW: 2751 { 2752 int na = oparg & 0xff; 2753 int nk = (oparg>>8) & 0xff; 2754 int flags = (opcode - CALL_FUNCTION) & 3; 2755 int n = na + 2 * nk; 2756 PyObject **pfunc, *func, **sp; 2757 PCALL(PCALL_ALL); 2758 if (flags & CALL_FLAG_VAR) 2759 n++; 2760 if (flags & CALL_FLAG_KW) 2761 n++; 2762 pfunc = stack_pointer - n - 1; 2763 func = *pfunc; 2764 2765 if (PyMethod_Check(func) 2766 && PyMethod_GET_SELF(func) != NULL) { 2767 PyObject *self = PyMethod_GET_SELF(func); 2768 Py_INCREF(self); 2769 func = PyMethod_GET_FUNCTION(func); 2770 Py_INCREF(func); 2771 Py_DECREF(*pfunc); 2772 *pfunc = self; 2773 na++; 2774 } else 2775 Py_INCREF(func); 2776 sp = stack_pointer; 2777 READ_TIMESTAMP(intr0); 2778 x = ext_do_call(func, &sp, flags, na, nk); 2779 READ_TIMESTAMP(intr1); 2780 stack_pointer = sp; 2781 Py_DECREF(func); 2782 2783 while (stack_pointer > pfunc) { 2784 w = POP(); 2785 Py_DECREF(w); 2786 } 2787 PUSH(x); 2788 if (x != NULL) 2789 continue; 2790 break; 2791 } 2792 2793 case MAKE_FUNCTION: 2794 v = POP(); /* code object */ 2795 x = PyFunction_New(v, f->f_globals); 2796 Py_DECREF(v); 2797 /* XXX Maybe this should be a separate opcode? */ 2798 if (x != NULL && oparg > 0) { 2799 v = PyTuple_New(oparg); 2800 if (v == NULL) { 2801 Py_DECREF(x); 2802 x = NULL; 2803 break; 2804 } 2805 while (--oparg >= 0) { 2806 w = POP(); 2807 PyTuple_SET_ITEM(v, oparg, w); 2808 } 2809 err = PyFunction_SetDefaults(x, v); 2810 Py_DECREF(v); 2811 } 2812 PUSH(x); 2813 break; 2814 2815 case MAKE_CLOSURE: 2816 { 2817 v = POP(); /* code object */ 2818 x = PyFunction_New(v, f->f_globals); 2819 Py_DECREF(v); 2820 if (x != NULL) { 2821 v = POP(); 2822 if (PyFunction_SetClosure(x, v) != 0) { 2823 /* Can't happen unless bytecode is corrupt. */ 2824 why = WHY_EXCEPTION; 2825 } 2826 Py_DECREF(v); 2827 } 2828 if (x != NULL && oparg > 0) { 2829 v = PyTuple_New(oparg); 2830 if (v == NULL) { 2831 Py_DECREF(x); 2832 x = NULL; 2833 break; 2834 } 2835 while (--oparg >= 0) { 2836 w = POP(); 2837 PyTuple_SET_ITEM(v, oparg, w); 2838 } 2839 if (PyFunction_SetDefaults(x, v) != 0) { 2840 /* Can't happen unless 2841 PyFunction_SetDefaults changes. */ 2842 why = WHY_EXCEPTION; 2843 } 2844 Py_DECREF(v); 2845 } 2846 PUSH(x); 2847 break; 2848 } 2849 2850 case BUILD_SLICE: 2851 if (oparg == 3) 2852 w = POP(); 2853 else 2854 w = NULL; 2855 v = POP(); 2856 u = TOP(); 2857 x = PySlice_New(u, v, w); 2858 Py_DECREF(u); 2859 Py_DECREF(v); 2860 Py_XDECREF(w); 2861 SET_TOP(x); 2862 if (x != NULL) continue; 2863 break; 2864 2865 case EXTENDED_ARG: 2866 opcode = NEXTOP(); 2867 oparg = oparg<<16 | NEXTARG(); 2868 goto dispatch_opcode; 2869 2870 default: 2871 fprintf(stderr, 2872 "XXX lineno: %d, opcode: %d\n", 2873 PyFrame_GetLineNumber(f), 2874 opcode); 2875 PyErr_SetString(PyExc_SystemError, "unknown opcode"); 2876 why = WHY_EXCEPTION; 2877 break; 2878 2879 #ifdef CASE_TOO_BIG 2880 } 2881 #endif 2882 2883 } /* switch */ 2884 2885 on_error: 2886 2887 READ_TIMESTAMP(inst1); 2888 2889 /* Quickly continue if no error occurred */ 2890 2891 if (why == WHY_NOT) { 2892 if (err == 0 && x != NULL) { 2893 #ifdef CHECKEXC 2894 /* This check is expensive! */ 2895 if (PyErr_Occurred()) 2896 fprintf(stderr, 2897 "XXX undetected error\n"); 2898 else { 2899 #endif 2900 READ_TIMESTAMP(loop1); 2901 continue; /* Normal, fast path */ 2902 #ifdef CHECKEXC 2903 } 2904 #endif 2905 } 2906 why = WHY_EXCEPTION; 2907 x = Py_None; 2908 err = 0; 2909 } 2910 2911 /* Double-check exception status */ 2912 2913 if (why == WHY_EXCEPTION || why == WHY_RERAISE) { 2914 if (!PyErr_Occurred()) { 2915 PyErr_SetString(PyExc_SystemError, 2916 "error return without exception set"); 2917 why = WHY_EXCEPTION; 2918 } 2919 } 2920 #ifdef CHECKEXC 2921 else { 2922 /* This check is expensive! */ 2923 if (PyErr_Occurred()) { 2924 char buf[128]; 2925 sprintf(buf, "Stack unwind with exception " 2926 "set and why=%d", why); 2927 Py_FatalError(buf); 2928 } 2929 } 2930 #endif 2931 2932 /* Log traceback info if this is a real exception */ 2933 2934 if (why == WHY_EXCEPTION) { 2935 PyTraceBack_Here(f); 2936 2937 if (tstate->c_tracefunc != NULL) 2938 call_exc_trace(tstate->c_tracefunc, 2939 tstate->c_traceobj, f); 2940 } 2941 2942 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ 2943 2944 if (why == WHY_RERAISE) 2945 why = WHY_EXCEPTION; 2946 2947 /* Unwind stacks if a (pseudo) exception occurred */ 2948 2949 fast_block_end: 2950 while (why != WHY_NOT && f->f_iblock > 0) { 2951 /* Peek at the current block. */ 2952 PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1]; 2953 2954 assert(why != WHY_YIELD); 2955 if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) { 2956 why = WHY_NOT; 2957 JUMPTO(PyInt_AS_LONG(retval)); 2958 Py_DECREF(retval); 2959 break; 2960 } 2961 2962 /* Now we have to pop the block. */ 2963 f->f_iblock--; 2964 2965 while (STACK_LEVEL() > b->b_level) { 2966 v = POP(); 2967 Py_XDECREF(v); 2968 } 2969 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { 2970 why = WHY_NOT; 2971 JUMPTO(b->b_handler); 2972 break; 2973 } 2974 if (b->b_type == SETUP_FINALLY || 2975 (b->b_type == SETUP_EXCEPT && 2976 why == WHY_EXCEPTION) || 2977 b->b_type == SETUP_WITH) { 2978 if (why == WHY_EXCEPTION) { 2979 PyObject *exc, *val, *tb; 2980 PyErr_Fetch(&exc, &val, &tb); 2981 if (val == NULL) { 2982 val = Py_None; 2983 Py_INCREF(val); 2984 } 2985 /* Make the raw exception data 2986 available to the handler, 2987 so a program can emulate the 2988 Python main loop. Don't do 2989 this for 'finally'. */ 2990 if (b->b_type == SETUP_EXCEPT || 2991 b->b_type == SETUP_WITH) { 2992 PyErr_NormalizeException( 2993 &exc, &val, &tb); 2994 set_exc_info(tstate, 2995 exc, val, tb); 2996 } 2997 if (tb == NULL) { 2998 Py_INCREF(Py_None); 2999 PUSH(Py_None); 3000 } else 3001 PUSH(tb); 3002 PUSH(val); 3003 PUSH(exc); 3004 } 3005 else { 3006 if (why & (WHY_RETURN | WHY_CONTINUE)) 3007 PUSH(retval); 3008 v = PyInt_FromLong((long)why); 3009 PUSH(v); 3010 } 3011 why = WHY_NOT; 3012 JUMPTO(b->b_handler); 3013 break; 3014 } 3015 } /* unwind stack */ 3016 3017 /* End the loop if we still have an error (or return) */ 3018 3019 if (why != WHY_NOT) 3020 break; 3021 READ_TIMESTAMP(loop1); 3022 3023 } /* main loop */ 3024 3025 assert(why != WHY_YIELD); 3026 /* Pop remaining stack entries. */ 3027 while (!EMPTY()) { 3028 v = POP(); 3029 Py_XDECREF(v); 3030 } 3031 3032 if (why != WHY_RETURN) 3033 retval = NULL; 3034 3035 fast_yield: 3036 if (tstate->use_tracing) { 3037 if (tstate->c_tracefunc) { 3038 if (why == WHY_RETURN || why == WHY_YIELD) { 3039 if (call_trace(tstate->c_tracefunc, 3040 tstate->c_traceobj, f, 3041 PyTrace_RETURN, retval)) { 3042 Py_XDECREF(retval); 3043 retval = NULL; 3044 why = WHY_EXCEPTION; 3045 } 3046 } 3047 else if (why == WHY_EXCEPTION) { 3048 call_trace_protected(tstate->c_tracefunc, 3049 tstate->c_traceobj, f, 3050 PyTrace_RETURN, NULL); 3051 } 3052 } 3053 if (tstate->c_profilefunc) { 3054 if (why == WHY_EXCEPTION) 3055 call_trace_protected(tstate->c_profilefunc, 3056 tstate->c_profileobj, f, 3057 PyTrace_RETURN, NULL); 3058 else if (call_trace(tstate->c_profilefunc, 3059 tstate->c_profileobj, f, 3060 PyTrace_RETURN, retval)) { 3061 Py_XDECREF(retval); 3062 retval = NULL; 3063 why = WHY_EXCEPTION; 3064 }
Value stored to 'why' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'why' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'why' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'why' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'why' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'why' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'why' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'why' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

3065 } 3066 } 3067 3068 if (tstate->frame->f_exc_type != NULL) 3069 reset_exc_info(tstate); 3070 else { 3071 assert(tstate->frame->f_exc_value == NULL); 3072 assert(tstate->frame->f_exc_traceback == NULL); 3073 } 3074 3075 /* pop frame */ 3076 exit_eval_frame: 3077 if (PYTHON_FUNCTION_RETURN_ENABLED()) 3078 dtrace_return(f); 3079 3080 Py_LeaveRecursiveCall(); 3081 tstate->frame = f->f_back; 3082 3083 return retval; 3084 } 3085 3086 /* This is gonna seem *real weird*, but if you put some other code between 3087 PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust 3088 the test in the if statements in Misc/gdbinit (pystack and pystackv). */ 3089 3090 PyObject * 3091 PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, 3092 PyObject **args, int argcount, PyObject **kws, int kwcount, 3093 PyObject **defs, int defcount, PyObject *closure) 3094 { 3095 register PyFrameObject *f; 3096 register PyObject *retval = NULL; 3097 register PyObject **fastlocals, **freevars; 3098 PyThreadState *tstate = PyThreadState_GET(); 3099 PyObject *x, *u; 3100 3101 if (globals == NULL) { 3102 PyErr_SetString(PyExc_SystemError, 3103 "PyEval_EvalCodeEx: NULL globals"); 3104 return NULL; 3105 } 3106 3107 assert(tstate != NULL); 3108 assert(globals != NULL); 3109 f = PyFrame_New(tstate, co, globals, locals); 3110 if (f == NULL) 3111 return NULL; 3112 3113 fastlocals = f->f_localsplus; 3114 freevars = f->f_localsplus + co->co_nlocals; 3115 3116 if (co->co_argcount > 0 || 3117 co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) { 3118 int i; 3119 int n = argcount; 3120 PyObject *kwdict = NULL; 3121 if (co->co_flags & CO_VARKEYWORDS) { 3122 kwdict = PyDict_New(); 3123 if (kwdict == NULL) 3124 goto fail; 3125 i = co->co_argcount; 3126 if (co->co_flags & CO_VARARGS) 3127 i++; 3128 SETLOCAL(i, kwdict); 3129 } 3130 if (argcount > co->co_argcount) { 3131 if (!(co->co_flags & CO_VARARGS)) { 3132 PyErr_Format(PyExc_TypeError, 3133 "%.200s() takes %s %d " 3134 "argument%s (%d given)", 3135 PyString_AsString(co->co_name), 3136 defcount ? "at most" : "exactly", 3137 co->co_argcount, 3138 co->co_argcount == 1 ? "" : "s", 3139 argcount + kwcount); 3140 goto fail; 3141 } 3142 n = co->co_argcount; 3143 } 3144 for (i = 0; i < n; i++) { 3145 x = args[i]; 3146 Py_INCREF(x); 3147 SETLOCAL(i, x); 3148 } 3149 if (co->co_flags & CO_VARARGS) { 3150 u = PyTuple_New(argcount - n); 3151 if (u == NULL) 3152 goto fail; 3153 SETLOCAL(co->co_argcount, u); 3154 for (i = n; i < argcount; i++) { 3155 x = args[i]; 3156 Py_INCREF(x); 3157 PyTuple_SET_ITEM(u, i-n, x); 3158 } 3159 } 3160 for (i = 0; i < kwcount; i++) { 3161 PyObject **co_varnames; 3162 PyObject *keyword = kws[2*i]; 3163 PyObject *value = kws[2*i + 1]; 3164 int j; 3165 if (keyword == NULL || !(PyString_Check(keyword) 3166 #ifdef Py_USING_UNICODE 3167 || PyUnicode_Check(keyword) 3168 #endif 3169 )) { 3170 PyErr_Format(PyExc_TypeError, 3171 "%.200s() keywords must be strings", 3172 PyString_AsString(co->co_name)); 3173 goto fail; 3174 } 3175 /* Speed hack: do raw pointer compares. As names are 3176 normally interned this should almost always hit. */ 3177 co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item; 3178 for (j = 0; j < co->co_argcount; j++) { 3179 PyObject *nm = co_varnames[j]; 3180 if (nm == keyword) 3181 goto kw_found; 3182 } 3183 /* Slow fallback, just in case */ 3184 for (j = 0; j < co->co_argcount; j++) { 3185 PyObject *nm = co_varnames[j]; 3186 int cmp = PyObject_RichCompareBool( 3187 keyword, nm, Py_EQ); 3188 if (cmp > 0) 3189 goto kw_found; 3190 else if (cmp < 0) 3191 goto fail; 3192 } 3193 if (kwdict == NULL) { 3194 PyObject *kwd_str = kwd_as_string(keyword); 3195 if (kwd_str) { 3196 PyErr_Format(PyExc_TypeError, 3197 "%.200s() got an unexpected " 3198 "keyword argument '%.400s'", 3199 PyString_AsString(co->co_name), 3200 PyString_AsString(kwd_str)); 3201 Py_DECREF(kwd_str); 3202 } 3203 goto fail; 3204 } 3205 PyDict_SetItem(kwdict, keyword, value); 3206 continue; 3207 kw_found: 3208 if (GETLOCAL(j) != NULL) { 3209 PyObject *kwd_str = kwd_as_string(keyword); 3210 if (kwd_str) { 3211 PyErr_Format(PyExc_TypeError, 3212 "%.200s() got multiple " 3213 "values for keyword " 3214 "argument '%.400s'", 3215 PyString_AsString(co->co_name), 3216 PyString_AsString(kwd_str)); 3217 Py_DECREF(kwd_str); 3218 } 3219 goto fail; 3220 } 3221 Py_INCREF(value); 3222 SETLOCAL(j, value); 3223 } 3224 if (argcount < co->co_argcount) { 3225 int m = co->co_argcount - defcount; 3226 for (i = argcount; i < m; i++) { 3227 if (GETLOCAL(i) == NULL) { 3228 int j, given = 0; 3229 for (j = 0; j < co->co_argcount; j++) 3230 if (GETLOCAL(j)) 3231 given++; 3232 PyErr_Format(PyExc_TypeError, 3233 "%.200s() takes %s %d " 3234 "argument%s (%d given)", 3235 PyString_AsString(co->co_name), 3236 ((co->co_flags & CO_VARARGS) || 3237 defcount) ? "at least" 3238 : "exactly", 3239 m, m == 1 ? "" : "s", given); 3240 goto fail; 3241 } 3242 } 3243 if (n > m) 3244 i = n - m; 3245 else 3246 i = 0; 3247 for (; i < defcount; i++) { 3248 if (GETLOCAL(m+i) == NULL) { 3249 PyObject *def = defs[i]; 3250 Py_INCREF(def); 3251 SETLOCAL(m+i, def); 3252 } 3253 } 3254 } 3255 } 3256 else if (argcount > 0 || kwcount > 0) { 3257 PyErr_Format(PyExc_TypeError, 3258 "%.200s() takes no arguments (%d given)", 3259 PyString_AsString(co->co_name), 3260 argcount + kwcount); 3261 goto fail; 3262 } 3263 /* Allocate and initialize storage for cell vars, and copy free 3264 vars into frame. This isn't too efficient right now. */ 3265 if (PyTuple_GET_SIZE(co->co_cellvars)) { 3266 int i, j, nargs, found; 3267 char *cellname, *argname; 3268 PyObject *c; 3269 3270 nargs = co->co_argcount; 3271 if (co->co_flags & CO_VARARGS) 3272 nargs++; 3273 if (co->co_flags & CO_VARKEYWORDS) 3274 nargs++; 3275 3276 /* Initialize each cell var, taking into account 3277 cell vars that are initialized from arguments. 3278 3279 Should arrange for the compiler to put cellvars 3280 that are arguments at the beginning of the cellvars 3281 list so that we can march over it more efficiently? 3282 */ 3283 for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) { 3284 cellname = PyString_AS_STRING( 3285 PyTuple_GET_ITEM(co->co_cellvars, i)); 3286 found = 0; 3287 for (j = 0; j < nargs; j++) { 3288 argname = PyString_AS_STRING( 3289 PyTuple_GET_ITEM(co->co_varnames, j)); 3290 if (strcmp(cellname, argname) == 0) { 3291 c = PyCell_New(GETLOCAL(j)); 3292 if (c == NULL) 3293 goto fail; 3294 GETLOCAL(co->co_nlocals + i) = c; 3295 found = 1; 3296 break; 3297 } 3298 } 3299 if (found == 0) { 3300 c = PyCell_New(NULL); 3301 if (c == NULL) 3302 goto fail; 3303 SETLOCAL(co->co_nlocals + i, c); 3304 } 3305 } 3306 } 3307 if (PyTuple_GET_SIZE(co->co_freevars)) { 3308 int i; 3309 for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { 3310 PyObject *o = PyTuple_GET_ITEM(closure, i); 3311 Py_INCREF(o); 3312 freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; 3313 } 3314 } 3315 3316 if (co->co_flags & CO_GENERATOR) { 3317 /* Don't need to keep the reference to f_back, it will be set 3318 * when the generator is resumed. */ 3319 Py_XDECREF(f->f_back); 3320 f->f_back = NULL; 3321 3322 PCALL(PCALL_GENERATOR); 3323 3324 /* Create a new generator that owns the ready to run frame 3325 * and return that as the value. */ 3326 return PyGen_New(f); 3327 } 3328 3329 retval = PyEval_EvalFrameEx(f,0); 3330 3331 fail: /* Jump here from prelude on failure */ 3332 3333 /* decref'ing the frame can cause __del__ methods to get invoked, 3334 which can call back into Python. While we're done with the 3335 current Python frame (f), the associated C stack is still in use, 3336 so recursion_depth must be boosted for the duration. 3337 */ 3338 assert(tstate != NULL); 3339 ++tstate->recursion_depth; 3340 Py_DECREF(f); 3341 --tstate->recursion_depth; 3342 return retval; 3343 } 3344 3345 3346 static PyObject * 3347 special_lookup(PyObject *o, char *meth, PyObject **cache) 3348 { 3349 PyObject *res; 3350 if (PyInstance_Check(o)) { 3351 if (!*cache) 3352 return PyObject_GetAttrString(o, meth); 3353 else 3354 return PyObject_GetAttr(o, *cache); 3355 } 3356 res = _PyObject_LookupSpecial(o, meth, cache); 3357 if (res == NULL && !PyErr_Occurred()) { 3358 PyErr_SetObject(PyExc_AttributeError, *cache); 3359 return NULL; 3360 } 3361 return res; 3362 } 3363 3364 3365 static PyObject * 3366 kwd_as_string(PyObject *kwd) { 3367 #ifdef Py_USING_UNICODE 3368 if (PyString_Check(kwd)) { 3369 #else 3370 assert(PyString_Check(kwd)); 3371 #endif 3372 Py_INCREF(kwd); 3373 return kwd; 3374 #ifdef Py_USING_UNICODE 3375 } 3376 return _PyUnicode_AsDefaultEncodedString(kwd, "replace"); 3377 #endif 3378 } 3379 3380 3381 /* Implementation notes for set_exc_info() and reset_exc_info(): 3382 3383 - Below, 'exc_ZZZ' stands for 'exc_type', 'exc_value' and 3384 'exc_traceback'. These always travel together. 3385 3386 - tstate->curexc_ZZZ is the "hot" exception that is set by 3387 PyErr_SetString(), cleared by PyErr_Clear(), and so on. 3388 3389 - Once an exception is caught by an except clause, it is transferred 3390 from tstate->curexc_ZZZ to tstate->exc_ZZZ, from which sys.exc_info() 3391 can pick it up. This is the primary task of set_exc_info(). 3392 XXX That can't be right: set_exc_info() doesn't look at tstate->curexc_ZZZ. 3393 3394 - Now let me explain the complicated dance with frame->f_exc_ZZZ. 3395 3396 Long ago, when none of this existed, there were just a few globals: 3397 one set corresponding to the "hot" exception, and one set 3398 corresponding to sys.exc_ZZZ. (Actually, the latter weren't C 3399 globals; they were simply stored as sys.exc_ZZZ. For backwards 3400 compatibility, they still are!) The problem was that in code like 3401 this: 3402 3403 try: 3404 "something that may fail" 3405 except "some exception": 3406 "do something else first" 3407 "print the exception from sys.exc_ZZZ." 3408 3409 if "do something else first" invoked something that raised and caught 3410 an exception, sys.exc_ZZZ were overwritten. That was a frequent 3411 cause of subtle bugs. I fixed this by changing the semantics as 3412 follows: 3413 3414 - Within one frame, sys.exc_ZZZ will hold the last exception caught 3415 *in that frame*. 3416 3417 - But initially, and as long as no exception is caught in a given 3418 frame, sys.exc_ZZZ will hold the last exception caught in the 3419 previous frame (or the frame before that, etc.). 3420 3421 The first bullet fixed the bug in the above example. The second 3422 bullet was for backwards compatibility: it was (and is) common to 3423 have a function that is called when an exception is caught, and to 3424 have that function access the caught exception via sys.exc_ZZZ. 3425 (Example: traceback.print_exc()). 3426 3427 At the same time I fixed the problem that sys.exc_ZZZ weren't 3428 thread-safe, by introducing sys.exc_info() which gets it from tstate; 3429 but that's really a separate improvement. 3430 3431 The reset_exc_info() function in ceval.c restores the tstate->exc_ZZZ 3432 variables to what they were before the current frame was called. The 3433 set_exc_info() function saves them on the frame so that 3434 reset_exc_info() can restore them. The invariant is that 3435 frame->f_exc_ZZZ is NULL iff the current frame never caught an 3436 exception (where "catching" an exception applies only to successful 3437 except clauses); and if the current frame ever caught an exception, 3438 frame->f_exc_ZZZ is the exception that was stored in tstate->exc_ZZZ 3439 at the start of the current frame. 3440 3441 */ 3442 3443 static void 3444 set_exc_info(PyThreadState *tstate, 3445 PyObject *type, PyObject *value, PyObject *tb) 3446 { 3447 PyFrameObject *frame = tstate->frame; 3448 PyObject *tmp_type, *tmp_value, *tmp_tb; 3449 3450 assert(type != NULL); 3451 assert(frame != NULL); 3452 if (frame->f_exc_type == NULL) { 3453 assert(frame->f_exc_value == NULL); 3454 assert(frame->f_exc_traceback == NULL); 3455 /* This frame didn't catch an exception before. */ 3456 /* Save previous exception of this thread in this frame. */ 3457 if (tstate->exc_type == NULL) { 3458 /* XXX Why is this set to Py_None? */ 3459 Py_INCREF(Py_None); 3460 tstate->exc_type = Py_None; 3461 } 3462 Py_INCREF(tstate->exc_type); 3463 Py_XINCREF(tstate->exc_value); 3464 Py_XINCREF(tstate->exc_traceback); 3465 frame->f_exc_type = tstate->exc_type; 3466 frame->f_exc_value = tstate->exc_value; 3467 frame->f_exc_traceback = tstate->exc_traceback; 3468 } 3469 /* Set new exception for this thread. */ 3470 tmp_type = tstate->exc_type; 3471 tmp_value = tstate->exc_value; 3472 tmp_tb = tstate->exc_traceback; 3473 Py_INCREF(type); 3474 Py_XINCREF(value); 3475 Py_XINCREF(tb); 3476 tstate->exc_type = type; 3477 tstate->exc_value = value; 3478 tstate->exc_traceback = tb; 3479 Py_XDECREF(tmp_type); 3480 Py_XDECREF(tmp_value); 3481 Py_XDECREF(tmp_tb); 3482 /* For b/w compatibility */ 3483 PySys_SetObject("exc_type", type); 3484 PySys_SetObject("exc_value", value); 3485 PySys_SetObject("exc_traceback", tb); 3486 } 3487 3488 static void 3489 reset_exc_info(PyThreadState *tstate) 3490 { 3491 PyFrameObject *frame; 3492 PyObject *tmp_type, *tmp_value, *tmp_tb; 3493 3494 /* It's a precondition that the thread state's frame caught an 3495 * exception -- verify in a debug build. 3496 */ 3497 assert(tstate != NULL); 3498 frame = tstate->frame; 3499 assert(frame != NULL); 3500 assert(frame->f_exc_type != NULL); 3501 3502 /* Copy the frame's exception info back to the thread state. */ 3503 tmp_type = tstate->exc_type; 3504 tmp_value = tstate->exc_value; 3505 tmp_tb = tstate->exc_traceback; 3506 Py_INCREF(frame->f_exc_type); 3507 Py_XINCREF(frame->f_exc_value); 3508 Py_XINCREF(frame->f_exc_traceback); 3509 tstate->exc_type = frame->f_exc_type; 3510 tstate->exc_value = frame->f_exc_value; 3511 tstate->exc_traceback = frame->f_exc_traceback; 3512 Py_XDECREF(tmp_type); 3513 Py_XDECREF(tmp_value); 3514 Py_XDECREF(tmp_tb); 3515 3516 /* For b/w compatibility */ 3517 PySys_SetObject("exc_type", frame->f_exc_type); 3518 PySys_SetObject("exc_value", frame->f_exc_value); 3519 PySys_SetObject("exc_traceback", frame->f_exc_traceback); 3520 3521 /* Clear the frame's exception info. */ 3522 tmp_type = frame->f_exc_type; 3523 tmp_value = frame->f_exc_value; 3524 tmp_tb = frame->f_exc_traceback; 3525 frame->f_exc_type = NULL; 3526 frame->f_exc_value = NULL; 3527 frame->f_exc_traceback = NULL; 3528 Py_DECREF(tmp_type); 3529 Py_XDECREF(tmp_value); 3530 Py_XDECREF(tmp_tb); 3531 } 3532 3533 /* Logic for the raise statement (too complicated for inlining). 3534 This *consumes* a reference count to each of its arguments. */ 3535 static enum why_code 3536 do_raise(PyObject *type, PyObject *value, PyObject *tb) 3537 { 3538 if (type == NULL) { 3539 /* Reraise */ 3540 PyThreadState *tstate = PyThreadState_GET(); 3541 type = tstate->exc_type == NULL ? Py_None : tstate->exc_type; 3542 value = tstate->exc_value; 3543 tb = tstate->exc_traceback; 3544 Py_XINCREF(type); 3545 Py_XINCREF(value); 3546 Py_XINCREF(tb); 3547 } 3548 3549 /* We support the following forms of raise: 3550 raise <class>, <classinstance> 3551 raise <class>, <argument tuple> 3552 raise <class>, None 3553 raise <class>, <argument> 3554 raise <classinstance>, None 3555 raise <string>, <object> 3556 raise <string>, None 3557 3558 An omitted second argument is the same as None. 3559 3560 In addition, raise <tuple>, <anything> is the same as 3561 raising the tuple's first item (and it better have one!); 3562 this rule is applied recursively. 3563 3564 Finally, an optional third argument can be supplied, which 3565 gives the traceback to be substituted (useful when 3566 re-raising an exception after examining it). */ 3567 3568 /* First, check the traceback argument, replacing None with 3569 NULL. */ 3570 if (tb == Py_None) { 3571 Py_DECREF(tb); 3572 tb = NULL; 3573 } 3574 else if (tb != NULL && !PyTraceBack_Check(tb)) { 3575 PyErr_SetString(PyExc_TypeError, 3576 "raise: arg 3 must be a traceback or None"); 3577 goto raise_error; 3578 } 3579 3580 /* Next, replace a missing value with None */ 3581 if (value == NULL) { 3582 value = Py_None; 3583 Py_INCREF(value); 3584 } 3585 3586 /* Next, repeatedly, replace a tuple exception with its first item */ 3587 while (PyTuple_Check(type) && PyTuple_Size(type) > 0) { 3588 PyObject *tmp = type; 3589 type = PyTuple_GET_ITEM(type, 0); 3590 Py_INCREF(type); 3591 Py_DECREF(tmp); 3592 } 3593 3594 if (PyExceptionClass_Check(type)) { 3595 PyErr_NormalizeException(&type, &value, &tb); 3596 if (!PyExceptionInstance_Check(value)) { 3597 PyErr_Format(PyExc_TypeError, 3598 "calling %s() should have returned an instance of " 3599 "BaseException, not '%s'", 3600 ((PyTypeObject *)type)->tp_name, 3601 Py_TYPE(value)->tp_name); 3602 goto raise_error; 3603 } 3604 } 3605 else if (PyExceptionInstance_Check(type)) { 3606 /* Raising an instance. The value should be a dummy. */ 3607 if (value != Py_None) { 3608 PyErr_SetString(PyExc_TypeError, 3609 "instance exception may not have a separate value"); 3610 goto raise_error; 3611 } 3612 else { 3613 /* Normalize to raise <class>, <instance> */ 3614 Py_DECREF(value); 3615 value = type; 3616 type = PyExceptionInstance_Class(type); 3617 Py_INCREF(type); 3618 } 3619 } 3620 else { 3621 /* Not something you can raise. You get an exception 3622 anyway, just not what you specified :-) */ 3623 PyErr_Format(PyExc_TypeError, 3624 "exceptions must be old-style classes or " 3625 "derived from BaseException, not %s", 3626 type->ob_type->tp_name); 3627 goto raise_error; 3628 } 3629 3630 assert(PyExceptionClass_Check(type)); 3631 if (Py_Py3kWarningFlag && PyClass_Check(type)) { 3632 if (PyErr_WarnEx(PyExc_DeprecationWarning, 3633 "exceptions must derive from BaseException " 3634 "in 3.x", 1) < 0) 3635 goto raise_error; 3636 } 3637 3638 PyErr_Restore(type, value, tb); 3639 if (tb == NULL) 3640 return WHY_EXCEPTION; 3641 else 3642 return WHY_RERAISE; 3643 raise_error: 3644 Py_XDECREF(value); 3645 Py_XDECREF(type); 3646 Py_XDECREF(tb); 3647 return WHY_EXCEPTION; 3648 } 3649 3650 /* Iterate v argcnt times and store the results on the stack (via decreasing 3651 sp). Return 1 for success, 0 if error. */ 3652 3653 static int 3654 unpack_iterable(PyObject *v, int argcnt, PyObject **sp) 3655 { 3656 int i = 0; 3657 PyObject *it; /* iter(v) */ 3658 PyObject *w; 3659 3660 assert(v != NULL); 3661 3662 it = PyObject_GetIter(v); 3663 if (it == NULL) 3664 goto Error; 3665 3666 for (; i < argcnt; i++) { 3667 w = PyIter_Next(it); 3668 if (w == NULL) { 3669 /* Iterator done, via error or exhaustion. */ 3670 if (!PyErr_Occurred()) { 3671 PyErr_Format(PyExc_ValueError, 3672 "need more than %d value%s to unpack", 3673 i, i == 1 ? "" : "s"); 3674 } 3675 goto Error; 3676 } 3677 *--sp = w; 3678 } 3679 3680 /* We better have exhausted the iterator now. */ 3681 w = PyIter_Next(it); 3682 if (w == NULL) { 3683 if (PyErr_Occurred()) 3684 goto Error; 3685 Py_DECREF(it); 3686 return 1; 3687 } 3688 Py_DECREF(w); 3689 PyErr_SetString(PyExc_ValueError, "too many values to unpack"); 3690 /* fall through */ 3691 Error: 3692 for (; i > 0; i--, sp++) 3693 Py_DECREF(*sp); 3694 Py_XDECREF(it); 3695 return 0; 3696 } 3697 3698 3699 #ifdef LLTRACE 3700 static int 3701 prtrace(PyObject *v, char *str) 3702 { 3703 printf("%s ", str); 3704 if (PyObject_Print(v, stdout, 0) != 0) 3705 PyErr_Clear(); /* Don't know what else to do */ 3706 printf("\n"); 3707 return 1; 3708 } 3709 #endif 3710 3711 static void 3712 call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f) 3713 { 3714 PyObject *type, *value, *traceback, *arg; 3715 int err; 3716 PyErr_Fetch(&type, &value, &traceback); 3717 if (value == NULL) { 3718 value = Py_None; 3719 Py_INCREF(value); 3720 } 3721 arg = PyTuple_Pack(3, type, value, traceback); 3722 if (arg == NULL) { 3723 PyErr_Restore(type, value, traceback); 3724 return; 3725 } 3726 err = call_trace(func, self, f, PyTrace_EXCEPTION, arg); 3727 Py_DECREF(arg); 3728 if (err == 0) 3729 PyErr_Restore(type, value, traceback); 3730 else { 3731 Py_XDECREF(type); 3732 Py_XDECREF(value); 3733 Py_XDECREF(traceback); 3734 } 3735 } 3736 3737 static int 3738 call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame, 3739 int what, PyObject *arg) 3740 { 3741 PyObject *type, *value, *traceback; 3742 int err; 3743 PyErr_Fetch(&type, &value, &traceback); 3744 err = call_trace(func, obj, frame, what, arg); 3745 if (err == 0) 3746 { 3747 PyErr_Restore(type, value, traceback); 3748 return 0; 3749 } 3750 else { 3751 Py_XDECREF(type); 3752 Py_XDECREF(value); 3753 Py_XDECREF(traceback); 3754 return -1; 3755 } 3756 } 3757 3758 static int 3759 call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame, 3760 int what, PyObject *arg) 3761 { 3762 register PyThreadState *tstate = frame->f_tstate; 3763 int result; 3764 if (tstate->tracing) 3765 return 0; 3766 tstate->tracing++; 3767 tstate->use_tracing = 0; 3768 result = func(obj, frame, what, arg); 3769 tstate->use_tracing = ((tstate->c_tracefunc != NULL) 3770 || (tstate->c_profilefunc != NULL)); 3771 tstate->tracing--; 3772 return result; 3773 } 3774 3775 PyObject * 3776 _PyEval_CallTracing(PyObject *func, PyObject *args) 3777 { 3778 PyFrameObject *frame = PyEval_GetFrame(); 3779 PyThreadState *tstate = frame->f_tstate; 3780 int save_tracing = tstate->tracing; 3781 int save_use_tracing = tstate->use_tracing; 3782 PyObject *result; 3783 3784 tstate->tracing = 0; 3785 tstate->use_tracing = ((tstate->c_tracefunc != NULL) 3786 || (tstate->c_profilefunc != NULL)); 3787 result = PyObject_Call(func, args, NULL); 3788 tstate->tracing = save_tracing; 3789 tstate->use_tracing = save_use_tracing; 3790 return result; 3791 } 3792 3793 /* See Objects/lnotab_notes.txt for a description of how tracing works. */ 3794 static int 3795 maybe_call_line_trace(Py_tracefunc func, PyObject *obj, 3796 PyFrameObject *frame, int *instr_lb, int *instr_ub, 3797 int *instr_prev) 3798 { 3799 int result = 0; 3800 int line = frame->f_lineno; 3801 3802 /* If the last instruction executed isn't in the current 3803 instruction window, reset the window. 3804 */ 3805 if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) { 3806 PyAddrPair bounds; 3807 line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, 3808 &bounds); 3809 *instr_lb = bounds.ap_lower; 3810 *instr_ub = bounds.ap_upper; 3811 } 3812 /* If the last instruction falls at the start of a line or if 3813 it represents a jump backwards, update the frame's line 3814 number and call the trace function. */ 3815 if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) { 3816 frame->f_lineno = line; 3817 result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); 3818 } 3819 *instr_prev = frame->f_lasti; 3820 return result; 3821 } 3822 3823 void 3824 PyEval_SetProfile(Py_tracefunc func, PyObject *arg) 3825 { 3826 PyThreadState *tstate = PyThreadState_GET(); 3827 PyObject *temp = tstate->c_profileobj; 3828 Py_XINCREF(arg); 3829 tstate->c_profilefunc = NULL; 3830 tstate->c_profileobj = NULL; 3831 /* Must make sure that tracing is not ignored if 'temp' is freed */ 3832 tstate->use_tracing = tstate->c_tracefunc != NULL; 3833 Py_XDECREF(temp); 3834 tstate->c_profilefunc = func; 3835 tstate->c_profileobj = arg; 3836 /* Flag that tracing or profiling is turned on */ 3837 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL); 3838 } 3839 3840 void 3841 PyEval_SetTrace(Py_tracefunc func, PyObject *arg) 3842 { 3843 PyThreadState *tstate = PyThreadState_GET(); 3844 PyObject *temp = tstate->c_traceobj; 3845 _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL); 3846 Py_XINCREF(arg); 3847 tstate->c_tracefunc = NULL; 3848 tstate->c_traceobj = NULL; 3849 /* Must make sure that profiling is not ignored if 'temp' is freed */ 3850 tstate->use_tracing = tstate->c_profilefunc != NULL; 3851 Py_XDECREF(temp); 3852 tstate->c_tracefunc = func; 3853 tstate->c_traceobj = arg; 3854 /* Flag that tracing or profiling is turned on */ 3855 tstate->use_tracing = ((func != NULL) 3856 || (tstate->c_profilefunc != NULL)); 3857 } 3858 3859 PyObject * 3860 PyEval_GetBuiltins(void) 3861 { 3862 PyFrameObject *current_frame = PyEval_GetFrame(); 3863 if (current_frame == NULL) 3864 return PyThreadState_GET()->interp->builtins; 3865 else 3866 return current_frame->f_builtins; 3867 } 3868 3869 PyObject * 3870 PyEval_GetLocals(void) 3871 { 3872 PyFrameObject *current_frame = PyEval_GetFrame(); 3873 if (current_frame == NULL) 3874 return NULL; 3875 PyFrame_FastToLocals(current_frame); 3876 return current_frame->f_locals; 3877 } 3878 3879 PyObject * 3880 PyEval_GetGlobals(void) 3881 { 3882 PyFrameObject *current_frame = PyEval_GetFrame(); 3883 if (current_frame == NULL) 3884 return NULL; 3885 else 3886 return current_frame->f_globals; 3887 } 3888 3889 PyFrameObject * 3890 PyEval_GetFrame(void) 3891 { 3892 PyThreadState *tstate = PyThreadState_GET(); 3893 return _PyThreadState_GetFrame(tstate); 3894 } 3895 3896 int 3897 PyEval_GetRestricted(void) 3898 { 3899 PyFrameObject *current_frame = PyEval_GetFrame(); 3900 return current_frame == NULL ? 0 : PyFrame_IsRestricted(current_frame); 3901 } 3902 3903 int 3904 PyEval_MergeCompilerFlags(PyCompilerFlags *cf) 3905 { 3906 PyFrameObject *current_frame = PyEval_GetFrame(); 3907 int result = cf->cf_flags != 0; 3908 3909 if (current_frame != NULL) { 3910 const int codeflags = current_frame->f_code->co_flags; 3911 const int compilerflags = codeflags & PyCF_MASK; 3912 if (compilerflags) { 3913 result = 1; 3914 cf->cf_flags |= compilerflags; 3915 } 3916 #if 0 /* future keyword */ 3917 if (codeflags & CO_GENERATOR_ALLOWED) { 3918 result = 1; 3919 cf->cf_flags |= CO_GENERATOR_ALLOWED; 3920 } 3921 #endif 3922 } 3923 return result; 3924 } 3925 3926 int 3927 Py_FlushLine(void) 3928 { 3929 PyObject *f = PySys_GetObject("stdout"); 3930 if (f == NULL) 3931 return 0; 3932 if (!PyFile_SoftSpace(f, 0)) 3933 return 0; 3934 return PyFile_WriteString("\n", f); 3935 } 3936 3937 3938 /* External interface to call any callable object. 3939 The arg must be a tuple or NULL. The kw must be a dict or NULL. */ 3940 3941 PyObject * 3942 PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw) 3943 { 3944 PyObject *result; 3945 3946 if (arg == NULL) { 3947 arg = PyTuple_New(0); 3948 if (arg == NULL) 3949 return NULL; 3950 } 3951 else if (!PyTuple_Check(arg)) { 3952 PyErr_SetString(PyExc_TypeError, 3953 "argument list must be a tuple"); 3954 return NULL; 3955 } 3956 else 3957 Py_INCREF(arg); 3958 3959 if (kw != NULL && !PyDict_Check(kw)) { 3960 PyErr_SetString(PyExc_TypeError, 3961 "keyword list must be a dictionary"); 3962 Py_DECREF(arg); 3963 return NULL; 3964 } 3965 3966 result = PyObject_Call(func, arg, kw); 3967 Py_DECREF(arg); 3968 return result; 3969 } 3970 3971 const char * 3972 PyEval_GetFuncName(PyObject *func) 3973 { 3974 if (PyMethod_Check(func)) 3975 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func)); 3976 else if (PyFunction_Check(func)) 3977 return PyString_AsString(((PyFunctionObject*)func)->func_name); 3978 else if (PyCFunction_Check(func)) 3979 return ((PyCFunctionObject*)func)->m_ml->ml_name; 3980 else if (PyClass_Check(func)) 3981 return PyString_AsString(((PyClassObject*)func)->cl_name); 3982 else if (PyInstance_Check(func)) { 3983 return PyString_AsString( 3984 ((PyInstanceObject*)func)->in_class->cl_name); 3985 } else { 3986 return func->ob_type->tp_name; 3987 } 3988 } 3989 3990 const char * 3991 PyEval_GetFuncDesc(PyObject *func) 3992 { 3993 if (PyMethod_Check(func)) 3994 return "()"; 3995 else if (PyFunction_Check(func)) 3996 return "()"; 3997 else if (PyCFunction_Check(func)) 3998 return "()"; 3999 else if (PyClass_Check(func)) 4000 return " constructor"; 4001 else if (PyInstance_Check(func)) { 4002 return " instance"; 4003 } else { 4004 return " object"; 4005 } 4006 } 4007 4008 static void 4009 err_args(PyObject *func, int flags, int nargs) 4010 { 4011 if (flags & METH_NOARGS) 4012 PyErr_Format(PyExc_TypeError, 4013 "%.200s() takes no arguments (%d given)", 4014 ((PyCFunctionObject *)func)->m_ml->ml_name, 4015 nargs); 4016 else 4017 PyErr_Format(PyExc_TypeError, 4018 "%.200s() takes exactly one argument (%d given)", 4019 ((PyCFunctionObject *)func)->m_ml->ml_name, 4020 nargs); 4021 } 4022 4023 #define C_TRACE(x, call) \ 4024 if (tstate->use_tracing && tstate->c_profilefunc) { \ 4025 if (call_trace(tstate->c_profilefunc, \ 4026 tstate->c_profileobj, \ 4027 tstate->frame, PyTrace_C_CALL, \ 4028 func)) { \ 4029 x = NULL; \ 4030 } \ 4031 else { \ 4032 x = call; \ 4033 if (tstate->c_profilefunc != NULL) { \ 4034 if (x == NULL) { \ 4035 call_trace_protected(tstate->c_profilefunc, \ 4036 tstate->c_profileobj, \ 4037 tstate->frame, PyTrace_C_EXCEPTION, \ 4038 func); \ 4039 /* XXX should pass (type, value, tb) */ \ 4040 } else { \ 4041 if (call_trace(tstate->c_profilefunc, \ 4042 tstate->c_profileobj, \ 4043 tstate->frame, PyTrace_C_RETURN, \ 4044 func)) { \ 4045 Py_DECREF(x); \ 4046 x = NULL; \ 4047 } \ 4048 } \ 4049 } \ 4050 } \ 4051 } else { \ 4052 x = call; \ 4053 } 4054 4055 static PyObject * 4056 call_function(PyObject ***pp_stack, int oparg 4057 #ifdef WITH_TSC 4058 , uint64* pintr0, uint64* pintr1 4059 #endif 4060 ) 4061 { 4062 int na = oparg & 0xff; 4063 int nk = (oparg>>8) & 0xff; 4064 int n = na + 2 * nk; 4065 PyObject **pfunc = (*pp_stack) - n - 1; 4066 PyObject *func = *pfunc; 4067 PyObject *x, *w; 4068 4069 /* Always dispatch PyCFunction first, because these are 4070 presumed to be the most frequent callable object. 4071 */ 4072 if (PyCFunction_Check(func) && nk == 0) { 4073 int flags = PyCFunction_GET_FLAGS(func); 4074 PyThreadState *tstate = PyThreadState_GET(); 4075 4076 PCALL(PCALL_CFUNCTION); 4077 if (flags & (METH_NOARGS | METH_O)) { 4078 PyCFunction meth = PyCFunction_GET_FUNCTION(func); 4079 PyObject *self = PyCFunction_GET_SELF(func); 4080 if (flags & METH_NOARGS && na == 0) { 4081 C_TRACE(x, (*meth)(self,NULL)); 4082 } 4083 else if (flags & METH_O && na == 1) { 4084 PyObject *arg = EXT_POP(*pp_stack); 4085 C_TRACE(x, (*meth)(self,arg)); 4086 Py_DECREF(arg); 4087 } 4088 else { 4089 err_args(func, flags, na); 4090 x = NULL; 4091 } 4092 } 4093 else { 4094 PyObject *callargs; 4095 callargs = load_args(pp_stack, na); 4096 READ_TIMESTAMP(*pintr0); 4097 C_TRACE(x, PyCFunction_Call(func,callargs,NULL)); 4098 READ_TIMESTAMP(*pintr1); 4099 Py_XDECREF(callargs); 4100 } 4101 } else { 4102 if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) { 4103 /* optimize access to bound methods */ 4104 PyObject *self = PyMethod_GET_SELF(func); 4105 PCALL(PCALL_METHOD); 4106 PCALL(PCALL_BOUND_METHOD); 4107 Py_INCREF(self); 4108 func = PyMethod_GET_FUNCTION(func); 4109 Py_INCREF(func); 4110 Py_DECREF(*pfunc); 4111 *pfunc = self; 4112 na++; 4113 n++; 4114 } else 4115 Py_INCREF(func); 4116 READ_TIMESTAMP(*pintr0); 4117 if (PyFunction_Check(func)) 4118 x = fast_function(func, pp_stack, n, na, nk); 4119 else 4120 x = do_call(func, pp_stack, na, nk); 4121 READ_TIMESTAMP(*pintr1); 4122 Py_DECREF(func); 4123 } 4124 4125 /* Clear the stack of the function object. Also removes 4126 the arguments in case they weren't consumed already 4127 (fast_function() and err_args() leave them on the stack). 4128 */ 4129 while ((*pp_stack) > pfunc) { 4130 w = EXT_POP(*pp_stack); 4131 Py_DECREF(w); 4132 PCALL(PCALL_POP); 4133 } 4134 return x; 4135 } 4136 4137 /* The fast_function() function optimize calls for which no argument 4138 tuple is necessary; the objects are passed directly from the stack. 4139 For the simplest case -- a function that takes only positional 4140 arguments and is called with only positional arguments -- it 4141 inlines the most primitive frame setup code from 4142 PyEval_EvalCodeEx(), which vastly reduces the checks that must be 4143 done before evaluating the frame. 4144 */ 4145 4146 static PyObject * 4147 fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk) 4148 { 4149 PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); 4150 PyObject *globals = PyFunction_GET_GLOBALS(func); 4151 PyObject *argdefs = PyFunction_GET_DEFAULTS(func); 4152 PyObject **d = NULL; 4153 int nd = 0; 4154 4155 PCALL(PCALL_FUNCTION); 4156 PCALL(PCALL_FAST_FUNCTION); 4157 if (argdefs == NULL && co->co_argcount == n && nk==0 && 4158 co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { 4159 PyFrameObject *f; 4160 PyObject *retval = NULL; 4161 PyThreadState *tstate = PyThreadState_GET(); 4162 PyObject **fastlocals, **stack; 4163 int i; 4164 4165 PCALL(PCALL_FASTER_FUNCTION); 4166 assert(globals != NULL); 4167 /* XXX Perhaps we should create a specialized 4168 PyFrame_New() that doesn't take locals, but does 4169 take builtins without sanity checking them. 4170 */ 4171 assert(tstate != NULL); 4172 f = PyFrame_New(tstate, co, globals, NULL); 4173 if (f == NULL) 4174 return NULL; 4175 4176 fastlocals = f->f_localsplus; 4177 stack = (*pp_stack) - n; 4178 4179 for (i = 0; i < n; i++) { 4180 Py_INCREF(*stack); 4181 fastlocals[i] = *stack++; 4182 } 4183 retval = PyEval_EvalFrameEx(f,0); 4184 ++tstate->recursion_depth; 4185 Py_DECREF(f); 4186 --tstate->recursion_depth; 4187 return retval; 4188 } 4189 if (argdefs != NULL) { 4190 d = &PyTuple_GET_ITEM(argdefs, 0); 4191 nd = Py_SIZE(argdefs); 4192 } 4193 return PyEval_EvalCodeEx(co, globals, 4194 (PyObject *)NULL, (*pp_stack)-n, na, 4195 (*pp_stack)-2*nk, nk, d, nd, 4196 PyFunction_GET_CLOSURE(func)); 4197 } 4198 4199 static PyObject * 4200 update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack, 4201 PyObject *func) 4202 { 4203 PyObject *kwdict = NULL; 4204 if (orig_kwdict == NULL) 4205 kwdict = PyDict_New(); 4206 else { 4207 kwdict = PyDict_Copy(orig_kwdict); 4208 Py_DECREF(orig_kwdict); 4209 } 4210 if (kwdict == NULL) 4211 return NULL; 4212 while (--nk >= 0) { 4213 int err; 4214 PyObject *value = EXT_POP(*pp_stack); 4215 PyObject *key = EXT_POP(*pp_stack); 4216 if (PyDict_GetItem(kwdict, key) != NULL) { 4217 PyErr_Format(PyExc_TypeError, 4218 "%.200s%s got multiple values " 4219 "for keyword argument '%.200s'", 4220 PyEval_GetFuncName(func), 4221 PyEval_GetFuncDesc(func), 4222 PyString_AsString(key)); 4223 Py_DECREF(key); 4224 Py_DECREF(value); 4225 Py_DECREF(kwdict); 4226 return NULL; 4227 } 4228 err = PyDict_SetItem(kwdict, key, value); 4229 Py_DECREF(key); 4230 Py_DECREF(value); 4231 if (err) { 4232 Py_DECREF(kwdict); 4233 return NULL; 4234 } 4235 } 4236 return kwdict; 4237 } 4238 4239 static PyObject * 4240 update_star_args(int nstack, int nstar, PyObject *stararg, 4241 PyObject ***pp_stack) 4242 { 4243 PyObject *callargs, *w; 4244 4245 callargs = PyTuple_New(nstack + nstar); 4246 if (callargs == NULL) { 4247 return NULL; 4248 } 4249 if (nstar) { 4250 int i; 4251 for (i = 0; i < nstar; i++) { 4252 PyObject *a = PyTuple_GET_ITEM(stararg, i); 4253 Py_INCREF(a); 4254 PyTuple_SET_ITEM(callargs, nstack + i, a); 4255 } 4256 } 4257 while (--nstack >= 0) { 4258 w = EXT_POP(*pp_stack); 4259 PyTuple_SET_ITEM(callargs, nstack, w); 4260 } 4261 return callargs; 4262 } 4263 4264 static PyObject * 4265 load_args(PyObject ***pp_stack, int na) 4266 { 4267 PyObject *args = PyTuple_New(na); 4268 PyObject *w; 4269 4270 if (args == NULL) 4271 return NULL; 4272 while (--na >= 0) { 4273 w = EXT_POP(*pp_stack); 4274 PyTuple_SET_ITEM(args, na, w); 4275 } 4276 return args; 4277 } 4278 4279 static PyObject * 4280 do_call(PyObject *func, PyObject ***pp_stack, int na, int nk) 4281 { 4282 PyObject *callargs = NULL; 4283 PyObject *kwdict = NULL; 4284 PyObject *result = NULL; 4285 4286 if (nk > 0) { 4287 kwdict = update_keyword_args(NULL, nk, pp_stack, func); 4288 if (kwdict == NULL) 4289 goto call_fail; 4290 } 4291 callargs = load_args(pp_stack, na); 4292 if (callargs == NULL) 4293 goto call_fail; 4294 #ifdef CALL_PROFILE 4295 /* At this point, we have to look at the type of func to 4296 update the call stats properly. Do it here so as to avoid 4297 exposing the call stats machinery outside ceval.c 4298 */ 4299 if (PyFunction_Check(func)) 4300 PCALL(PCALL_FUNCTION); 4301 else if (PyMethod_Check(func)) 4302 PCALL(PCALL_METHOD); 4303 else if (PyType_Check(func)) 4304 PCALL(PCALL_TYPE); 4305 else if (PyCFunction_Check(func)) 4306 PCALL(PCALL_CFUNCTION); 4307 else 4308 PCALL(PCALL_OTHER); 4309 #endif 4310 if (PyCFunction_Check(func)) { 4311 PyThreadState *tstate = PyThreadState_GET(); 4312 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); 4313 } 4314 else 4315 result = PyObject_Call(func, callargs, kwdict); 4316 call_fail: 4317 Py_XDECREF(callargs); 4318 Py_XDECREF(kwdict); 4319 return result; 4320 } 4321 4322 static PyObject * 4323 ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk) 4324 { 4325 int nstar = 0; 4326 PyObject *callargs = NULL; 4327 PyObject *stararg = NULL; 4328 PyObject *kwdict = NULL; 4329 PyObject *result = NULL; 4330 4331 if (flags & CALL_FLAG_KW) { 4332 kwdict = EXT_POP(*pp_stack); 4333 if (!PyDict_Check(kwdict)) { 4334 PyObject *d; 4335 d = PyDict_New(); 4336 if (d == NULL) 4337 goto ext_call_fail; 4338 if (PyDict_Update(d, kwdict) != 0) { 4339 Py_DECREF(d); 4340 /* PyDict_Update raises attribute 4341 * error (percolated from an attempt 4342 * to get 'keys' attribute) instead of 4343 * a type error if its second argument 4344 * is not a mapping. 4345 */ 4346 if (PyErr_ExceptionMatches(PyExc_AttributeError)) { 4347 PyErr_Format(PyExc_TypeError, 4348 "%.200s%.200s argument after ** " 4349 "must be a mapping, not %.200s", 4350 PyEval_GetFuncName(func), 4351 PyEval_GetFuncDesc(func), 4352 kwdict->ob_type->tp_name); 4353 } 4354 goto ext_call_fail; 4355 } 4356 Py_DECREF(kwdict); 4357 kwdict = d; 4358 } 4359 } 4360 if (flags & CALL_FLAG_VAR) { 4361 stararg = EXT_POP(*pp_stack); 4362 if (!PyTuple_Check(stararg)) { 4363 PyObject *t = NULL; 4364 t = PySequence_Tuple(stararg); 4365 if (t == NULL) { 4366 if (PyErr_ExceptionMatches(PyExc_TypeError)) { 4367 PyErr_Format(PyExc_TypeError, 4368 "%.200s%.200s argument after * " 4369 "must be a sequence, not %200s", 4370 PyEval_GetFuncName(func), 4371 PyEval_GetFuncDesc(func), 4372 stararg->ob_type->tp_name); 4373 } 4374 goto ext_call_fail; 4375 } 4376 Py_DECREF(stararg); 4377 stararg = t; 4378 } 4379 nstar = PyTuple_GET_SIZE(stararg); 4380 } 4381 if (nk > 0) { 4382 kwdict = update_keyword_args(kwdict, nk, pp_stack, func); 4383 if (kwdict == NULL) 4384 goto ext_call_fail; 4385 } 4386 callargs = update_star_args(na, nstar, stararg, pp_stack); 4387 if (callargs == NULL) 4388 goto ext_call_fail; 4389 #ifdef CALL_PROFILE 4390 /* At this point, we have to look at the type of func to 4391 update the call stats properly. Do it here so as to avoid 4392 exposing the call stats machinery outside ceval.c 4393 */ 4394 if (PyFunction_Check(func)) 4395 PCALL(PCALL_FUNCTION); 4396 else if (PyMethod_Check(func)) 4397 PCALL(PCALL_METHOD); 4398 else if (PyType_Check(func)) 4399 PCALL(PCALL_TYPE); 4400 else if (PyCFunction_Check(func)) 4401 PCALL(PCALL_CFUNCTION); 4402 else 4403 PCALL(PCALL_OTHER); 4404 #endif 4405 if (PyCFunction_Check(func)) { 4406 PyThreadState *tstate = PyThreadState_GET(); 4407 C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); 4408 } 4409 else 4410 result = PyObject_Call(func, callargs, kwdict); 4411 ext_call_fail: 4412 Py_XDECREF(callargs); 4413 Py_XDECREF(kwdict); 4414 Py_XDECREF(stararg); 4415 return result; 4416 } 4417 4418 /* Extract a slice index from a PyInt or PyLong or an object with the 4419 nb_index slot defined, and store in *pi. 4420 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX, 4421 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1. 4422 Return 0 on error, 1 on success. 4423 */ 4424 /* Note: If v is NULL, return success without storing into *pi. This 4425 is because_PyEval_SliceIndex() is called by apply_slice(), which can be 4426 called by the SLICE opcode with v and/or w equal to NULL. 4427 */ 4428 int 4429 _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi) 4430 { 4431 if (v != NULL) { 4432 Py_ssize_t x; 4433 if (PyInt_Check(v)) { 4434 /* XXX(nnorwitz): I think PyInt_AS_LONG is correct, 4435 however, it looks like it should be AsSsize_t. 4436 There should be a comment here explaining why. 4437 */ 4438 x = PyInt_AS_LONG(v); 4439 } 4440 else if (PyIndex_Check(v)) { 4441 x = PyNumber_AsSsize_t(v, NULL); 4442 if (x == -1 && PyErr_Occurred()) 4443 return 0; 4444 } 4445 else { 4446 PyErr_SetString(PyExc_TypeError, 4447 "slice indices must be integers or " 4448 "None or have an __index__ method"); 4449 return 0; 4450 } 4451 *pi = x; 4452 } 4453 return 1; 4454 } 4455 4456 #undef ISINDEX 4457 #define ISINDEX(x) ((x) == NULL || \ 4458 PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x)) 4459 4460 static PyObject * 4461 apply_slice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */ 4462 { 4463 PyTypeObject *tp = u->ob_type; 4464 PySequenceMethods *sq = tp->tp_as_sequence; 4465 4466 if (sq && sq->sq_slice && ISINDEX(v) && ISINDEX(w)) { 4467 Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX; 4468 if (!_PyEval_SliceIndex(v, &ilow)) 4469 return NULL; 4470 if (!_PyEval_SliceIndex(w, &ihigh)) 4471 return NULL; 4472 return PySequence_GetSlice(u, ilow, ihigh); 4473 } 4474 else { 4475 PyObject *slice = PySlice_New(v, w, NULL); 4476 if (slice != NULL) { 4477 PyObject *res = PyObject_GetItem(u, slice); 4478 Py_DECREF(slice); 4479 return res; 4480 } 4481 else 4482 return NULL; 4483 } 4484 } 4485 4486 static int 4487 assign_slice(PyObject *u, PyObject *v, PyObject *w, PyObject *x) 4488 /* u[v:w] = x */ 4489 { 4490 PyTypeObject *tp = u->ob_type; 4491 PySequenceMethods *sq = tp->tp_as_sequence; 4492 4493 if (sq && sq->sq_ass_slice && ISINDEX(v) && ISINDEX(w)) { 4494 Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX; 4495 if (!_PyEval_SliceIndex(v, &ilow)) 4496 return -1; 4497 if (!_PyEval_SliceIndex(w, &ihigh)) 4498 return -1; 4499 if (x == NULL) 4500 return PySequence_DelSlice(u, ilow, ihigh); 4501 else 4502 return PySequence_SetSlice(u, ilow, ihigh, x); 4503 } 4504 else { 4505 PyObject *slice = PySlice_New(v, w, NULL); 4506 if (slice != NULL) { 4507 int res; 4508 if (x != NULL) 4509 res = PyObject_SetItem(u, slice, x); 4510 else 4511 res = PyObject_DelItem(u, slice); 4512 Py_DECREF(slice); 4513 return res; 4514 } 4515 else 4516 return -1; 4517 } 4518 } 4519 4520 #define Py3kExceptionClass_Check(x) \ 4521 (PyType_Check((x)) && \ 4522 PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) 4523 4524 #define CANNOT_CATCH_MSG "catching classes that don't inherit from " \ 4525 "BaseException is not allowed in 3.x" 4526 4527 static PyObject * 4528 cmp_outcome(int op, register PyObject *v, register PyObject *w) 4529 { 4530 int res = 0; 4531 switch (op) { 4532 case PyCmp_IS: 4533 res = (v == w); 4534 break; 4535 case PyCmp_IS_NOT: 4536 res = (v != w); 4537 break; 4538 case PyCmp_IN: 4539 res = PySequence_Contains(w, v); 4540 if (res < 0) 4541 return NULL; 4542 break; 4543 case PyCmp_NOT_IN: 4544 res = PySequence_Contains(w, v); 4545 if (res < 0) 4546 return NULL; 4547 res = !res; 4548 break; 4549 case PyCmp_EXC_MATCH: 4550 if (PyTuple_Check(w)) { 4551 Py_ssize_t i, length; 4552 length = PyTuple_Size(w); 4553 for (i = 0; i < length; i += 1) { 4554 PyObject *exc = PyTuple_GET_ITEM(w, i); 4555 if (PyString_Check(exc)) { 4556 int ret_val; 4557 ret_val = PyErr_WarnEx( 4558 PyExc_DeprecationWarning, 4559 "catching of string " 4560 "exceptions is deprecated", 1); 4561 if (ret_val < 0) 4562 return NULL; 4563 } 4564 else if (Py_Py3kWarningFlag && 4565 !PyTuple_Check(exc) && 4566 !Py3kExceptionClass_Check(exc)) 4567 { 4568 int ret_val; 4569 ret_val = PyErr_WarnEx( 4570 PyExc_DeprecationWarning, 4571 CANNOT_CATCH_MSG, 1); 4572 if (ret_val < 0) 4573 return NULL; 4574 } 4575 } 4576 } 4577 else { 4578 if (PyString_Check(w)) { 4579 int ret_val; 4580 ret_val = PyErr_WarnEx( 4581 PyExc_DeprecationWarning, 4582 "catching of string " 4583 "exceptions is deprecated", 1); 4584 if (ret_val < 0) 4585 return NULL; 4586 } 4587 else if (Py_Py3kWarningFlag && 4588 !PyTuple_Check(w) && 4589 !Py3kExceptionClass_Check(w)) 4590 { 4591 int ret_val; 4592 ret_val = PyErr_WarnEx( 4593 PyExc_DeprecationWarning, 4594 CANNOT_CATCH_MSG, 1); 4595 if (ret_val < 0) 4596 return NULL; 4597 } 4598 } 4599 res = PyErr_GivenExceptionMatches(v, w); 4600 break; 4601 default: 4602 return PyObject_RichCompare(v, w, op); 4603 } 4604 v = res ? Py_True : Py_False; 4605 Py_INCREF(v); 4606 return v; 4607 } 4608 4609 static PyObject * 4610 import_from(PyObject *v, PyObject *name) 4611 { 4612 PyObject *x; 4613 4614 x = PyObject_GetAttr(v, name); 4615 if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { 4616 PyErr_Format(PyExc_ImportError, 4617 "cannot import name %.230s", 4618 PyString_AsString(name)); 4619 } 4620 return x; 4621 } 4622 4623 static int 4624 import_all_from(PyObject *locals, PyObject *v) 4625 { 4626 PyObject *all = PyObject_GetAttrString(v, "__all__"); 4627 PyObject *dict, *name, *value; 4628 int skip_leading_underscores = 0; 4629 int pos, err; 4630 4631 if (all == NULL) { 4632 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) 4633 return -1; /* Unexpected error */ 4634 PyErr_Clear(); 4635 dict = PyObject_GetAttrString(v, "__dict__"); 4636 if (dict == NULL) { 4637 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) 4638 return -1; 4639 PyErr_SetString(PyExc_ImportError, 4640 "from-import-* object has no __dict__ and no __all__"); 4641 return -1; 4642 } 4643 all = PyMapping_Keys(dict); 4644 Py_DECREF(dict); 4645 if (all == NULL) 4646 return -1; 4647 skip_leading_underscores = 1; 4648 } 4649 4650 for (pos = 0, err = 0; ; pos++) { 4651 name = PySequence_GetItem(all, pos); 4652 if (name == NULL) { 4653 if (!PyErr_ExceptionMatches(PyExc_IndexError)) 4654 err = -1; 4655 else 4656 PyErr_Clear(); 4657 break; 4658 } 4659 if (skip_leading_underscores && 4660 PyString_Check(name) && 4661 PyString_AS_STRING(name)[0] == '_') 4662 { 4663 Py_DECREF(name); 4664 continue; 4665 } 4666 value = PyObject_GetAttr(v, name); 4667 if (value == NULL) 4668 err = -1; 4669 else if (PyDict_CheckExact(locals)) 4670 err = PyDict_SetItem(locals, name, value); 4671 else 4672 err = PyObject_SetItem(locals, name, value); 4673 Py_DECREF(name); 4674 Py_XDECREF(value); 4675 if (err != 0) 4676 break; 4677 } 4678 Py_DECREF(all); 4679 return err; 4680 } 4681 4682 static PyObject * 4683 build_class(PyObject *methods, PyObject *bases, PyObject *name) 4684 { 4685 PyObject *metaclass = NULL, *result, *base; 4686 4687 if (PyDict_Check(methods)) 4688 metaclass = PyDict_GetItemString(methods, "__metaclass__"); 4689 if (metaclass != NULL) 4690 Py_INCREF(metaclass); 4691 else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) { 4692 base = PyTuple_GET_ITEM(bases, 0); 4693 metaclass = PyObject_GetAttrString(base, "__class__"); 4694 if (metaclass == NULL) { 4695 PyErr_Clear(); 4696 metaclass = (PyObject *)base->ob_type; 4697 Py_INCREF(metaclass); 4698 } 4699 } 4700 else { 4701 PyObject *g = PyEval_GetGlobals(); 4702 if (g != NULL && PyDict_Check(g)) 4703 metaclass = PyDict_GetItemString(g, "__metaclass__"); 4704 if (metaclass == NULL) 4705 metaclass = (PyObject *) &PyClass_Type; 4706 Py_INCREF(metaclass); 4707 } 4708 result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, 4709 NULL); 4710 Py_DECREF(metaclass); 4711 if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { 4712 /* A type error here likely means that the user passed 4713 in a base that was not a class (such the random module 4714 instead of the random.random type). Help them out with 4715 by augmenting the error message with more information.*/ 4716 4717 PyObject *ptype, *pvalue, *ptraceback; 4718 4719 PyErr_Fetch(&ptype, &pvalue, &ptraceback); 4720 if (PyString_Check(pvalue)) { 4721 PyObject *newmsg; 4722 newmsg = PyString_FromFormat( 4723 "Error when calling the metaclass bases\n" 4724 " %s", 4725 PyString_AS_STRING(pvalue)); 4726 if (newmsg != NULL) { 4727 Py_DECREF(pvalue); 4728 pvalue = newmsg; 4729 } 4730 } 4731 PyErr_Restore(ptype, pvalue, ptraceback); 4732 } 4733 return result; 4734 } 4735 4736 static int 4737 exec_statement(PyFrameObject *f, PyObject *prog, PyObject *globals, 4738 PyObject *locals) 4739 { 4740 int n; 4741 PyObject *v; 4742 int plain = 0; 4743 4744 if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None && 4745 ((n = PyTuple_Size(prog)) == 2 || n == 3)) { 4746 /* Backward compatibility hack */ 4747 globals = PyTuple_GetItem(prog, 1); 4748 if (n == 3) 4749 locals = PyTuple_GetItem(prog, 2); 4750 prog = PyTuple_GetItem(prog, 0); 4751 } 4752 if (globals == Py_None) { 4753 globals = PyEval_GetGlobals(); 4754 if (locals == Py_None) { 4755 locals = PyEval_GetLocals(); 4756 plain = 1; 4757 } 4758 if (!globals || !locals) { 4759 PyErr_SetString(PyExc_SystemError, 4760 "globals and locals cannot be NULL"); 4761 return -1; 4762 } 4763 } 4764 else if (locals == Py_None) 4765 locals = globals; 4766 if (!PyString_Check(prog) && 4767 #ifdef Py_USING_UNICODE 4768 !PyUnicode_Check(prog) && 4769 #endif 4770 !PyCode_Check(prog) && 4771 !PyFile_Check(prog)) { 4772 PyErr_SetString(PyExc_TypeError, 4773 "exec: arg 1 must be a string, file, or code object"); 4774 return -1; 4775 } 4776 if (!PyDict_Check(globals)) { 4777 PyErr_SetString(PyExc_TypeError, 4778 "exec: arg 2 must be a dictionary or None"); 4779 return -1; 4780 } 4781 if (!PyMapping_Check(locals)) { 4782 PyErr_SetString(PyExc_TypeError, 4783 "exec: arg 3 must be a mapping or None"); 4784 return -1; 4785 } 4786 if (PyDict_GetItemString(globals, "__builtins__") == NULL) 4787 PyDict_SetItemString(globals, "__builtins__", f->f_builtins); 4788 if (PyCode_Check(prog)) { 4789 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) { 4790 PyErr_SetString(PyExc_TypeError, 4791 "code object passed to exec may not contain free variables"); 4792 return -1; 4793 } 4794 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals); 4795 } 4796 else if (PyFile_Check(prog)) { 4797 FILE *fp = PyFile_AsFile(prog); 4798 char *name = PyString_AsString(PyFile_Name(prog)); 4799 PyCompilerFlags cf; 4800 if (name == NULL) 4801 return -1; 4802 cf.cf_flags = 0; 4803 if (PyEval_MergeCompilerFlags(&cf)) 4804 v = PyRun_FileFlags(fp, name, Py_file_input, globals, 4805 locals, &cf); 4806 else 4807 v = PyRun_File(fp, name, Py_file_input, globals, 4808 locals); 4809 } 4810 else { 4811 PyObject *tmp = NULL; 4812 char *str; 4813 PyCompilerFlags cf; 4814 cf.cf_flags = 0; 4815 #ifdef Py_USING_UNICODE 4816 if (PyUnicode_Check(prog)) { 4817 tmp = PyUnicode_AsUTF8String(prog); 4818 if (tmp == NULL) 4819 return -1; 4820 prog = tmp; 4821 cf.cf_flags |= PyCF_SOURCE_IS_UTF8; 4822 } 4823 #endif 4824 if (PyString_AsStringAndSize(prog, &str, NULL)) 4825 return -1; 4826 if (PyEval_MergeCompilerFlags(&cf)) 4827 v = PyRun_StringFlags(str, Py_file_input, globals, 4828 locals, &cf); 4829 else 4830 v = PyRun_String(str, Py_file_input, globals, locals); 4831 Py_XDECREF(tmp); 4832 } 4833 if (plain) 4834 PyFrame_LocalsToFast(f, 0); 4835 if (v == NULL) 4836 return -1; 4837 Py_DECREF(v); 4838 return 0; 4839 } 4840 4841 static void 4842 format_exc_check_arg(PyObject *exc, char *format_str, PyObject *obj) 4843 { 4844 char *obj_str; 4845 4846 if (!obj) 4847 return; 4848 4849 obj_str = PyString_AsString(obj); 4850 if (!obj_str) 4851 return; 4852 4853 PyErr_Format(exc, format_str, obj_str); 4854 } 4855 4856 static PyObject * 4857 string_concatenate(PyObject *v, PyObject *w, 4858 PyFrameObject *f, unsigned char *next_instr) 4859 { 4860 /* This function implements 'variable += expr' when both arguments 4861 are strings. */ 4862 Py_ssize_t v_len = PyString_GET_SIZE(v); 4863 Py_ssize_t w_len = PyString_GET_SIZE(w); 4864 Py_ssize_t new_len = v_len + w_len; 4865 if (new_len < 0) { 4866 PyErr_SetString(PyExc_OverflowError, 4867 "strings are too large to concat"); 4868 return NULL; 4869 } 4870 4871 if (v->ob_refcnt == 2) { 4872 /* In the common case, there are 2 references to the value 4873 * stored in 'variable' when the += is performed: one on the 4874 * value stack (in 'v') and one still stored in the 4875 * 'variable'. We try to delete the variable now to reduce 4876 * the refcnt to 1. 4877 */ 4878 switch (*next_instr) { 4879 case STORE_FAST: 4880 { 4881 int oparg = PEEKARG(); 4882 PyObject **fastlocals = f->f_localsplus; 4883 if (GETLOCAL(oparg) == v) 4884 SETLOCAL(oparg, NULL); 4885 break; 4886 } 4887 case STORE_DEREF: 4888 { 4889 PyObject **freevars = (f->f_localsplus + 4890 f->f_code->co_nlocals); 4891 PyObject *c = freevars[PEEKARG()]; 4892 if (PyCell_GET(c) == v) 4893 PyCell_Set(c, NULL); 4894 break; 4895 } 4896 case STORE_NAME: 4897 { 4898 PyObject *names = f->f_code->co_names; 4899 PyObject *name = GETITEM(names, PEEKARG()); 4900 PyObject *locals = f->f_locals; 4901 if (PyDict_CheckExact(locals) && 4902 PyDict_GetItem(locals, name) == v) { 4903 if (PyDict_DelItem(locals, name) != 0) { 4904 PyErr_Clear(); 4905 } 4906 } 4907 break; 4908 } 4909 } 4910 } 4911 4912 if (v->ob_refcnt == 1 && !PyString_CHECK_INTERNED(v)) { 4913 /* Now we own the last reference to 'v', so we can resize it 4914 * in-place. 4915 */ 4916 if (_PyString_Resize(&v, new_len) != 0) { 4917 /* XXX if _PyString_Resize() fails, 'v' has been 4918 * deallocated so it cannot be put back into 4919 * 'variable'. The MemoryError is raised when there 4920 * is no value in 'variable', which might (very 4921 * remotely) be a cause of incompatibilities. 4922 */ 4923 return NULL; 4924 } 4925 /* copy 'w' into the newly allocated area of 'v' */ 4926 memcpy(PyString_AS_STRING(v) + v_len, 4927 PyString_AS_STRING(w), w_len); 4928 return v; 4929 } 4930 else { 4931 /* When in-place resizing is not an option. */ 4932 PyString_Concat(&v, w); 4933 return v; 4934 } 4935 } 4936 4937 #ifdef DYNAMIC_EXECUTION_PROFILE 4938 4939 static PyObject * 4940 getarray(long a[256]) 4941 { 4942 int i; 4943 PyObject *l = PyList_New(256); 4944 if (l == NULL) return NULL; 4945 for (i = 0; i < 256; i++) { 4946 PyObject *x = PyInt_FromLong(a[i]); 4947 if (x == NULL) { 4948 Py_DECREF(l); 4949 return NULL; 4950 } 4951 PyList_SetItem(l, i, x); 4952 } 4953 for (i = 0; i < 256; i++) 4954 a[i] = 0; 4955 return l; 4956 } 4957 4958 PyObject * 4959 _Py_GetDXProfile(PyObject *self, PyObject *args) 4960 { 4961 #ifndef DXPAIRS 4962 return getarray(dxp); 4963 #else 4964 int i; 4965 PyObject *l = PyList_New(257); 4966 if (l == NULL) return NULL; 4967 for (i = 0; i < 257; i++) { 4968 PyObject *x = getarray(dxpairs[i]); 4969 if (x == NULL) { 4970 Py_DECREF(l); 4971 return NULL; 4972 } 4973 PyList_SetItem(l, i, x); 4974 } 4975 return l; 4976 #endif 4977 } 4978 4979 #endif