Python-2.7.3/Objects/object.c

Location Tool Test ID Function Issue
/builddir/build/BUILD/Python-2.7.3/Objects/object.c:1171:10 clang-analyzer Access to field 'ob_type' results in a dereference of a null pointer (loaded from variable 'name')*
/builddir/build/BUILD/Python-2.7.3/Objects/object.c:1171:10 clang-analyzer Access to field 'ob_type' results in a dereference of a null pointer (loaded from variable 'name')*
/builddir/build/BUILD/Python-2.7.3/Objects/object.c:2291:18 clang-analyzer Access to field '_ob_next' results in a dereference of a null pointer (loaded from variable 'op')
/builddir/build/BUILD/Python-2.7.3/Objects/object.c:2350:5 gcc implicit-function-declaration _PyObject_DebugTypeStats implicit declaration of function '_PySet_DebugMallocStats'
/builddir/build/BUILD/Python-2.7.3/Objects/object.c:2350:5 gcc implicit-function-declaration _PyObject_DebugTypeStats implicit declaration of function '_PySet_DebugMallocStats'
/builddir/build/BUILD/Python-2.7.3/Objects/object.c:2351:5 gcc implicit-function-declaration _PyObject_DebugTypeStats implicit declaration of function '_PyTuple_DebugMallocStats'
/builddir/build/BUILD/Python-2.7.3/Objects/object.c:2351:5 gcc implicit-function-declaration _PyObject_DebugTypeStats implicit declaration of function '_PyTuple_DebugMallocStats'
   1 /* Generic object operations; and implementation of None (NoObject) */
   2 
   3 #include "Python.h"
   4 #include "frameobject.h"
   5 
   6 #ifdef __cplusplus
   7 extern "C" {
   8 #endif
   9 
  10 #ifdef Py_REF_DEBUG
  11 Py_ssize_t _Py_RefTotal;
  12 
  13 Py_ssize_t
  14 _Py_GetRefTotal(void)
  15 {
  16     PyObject *o;
  17     Py_ssize_t total = _Py_RefTotal;
  18     /* ignore the references to the dummy object of the dicts and sets
  19        because they are not reliable and not useful (now that the
  20        hash table code is well-tested) */
  21     o = _PyDict_Dummy();
  22     if (o != NULL)
  23         total -= o->ob_refcnt;
  24     o = _PySet_Dummy();
  25     if (o != NULL)
  26         total -= o->ob_refcnt;
  27     return total;
  28 }
  29 #endif /* Py_REF_DEBUG */
  30 
  31 int Py_DivisionWarningFlag;
  32 int Py_Py3kWarningFlag;
  33 
  34 /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
  35    These are used by the individual routines for object creation.
  36    Do not call them otherwise, they do not initialize the object! */
  37 
  38 #ifdef Py_TRACE_REFS
  39 /* Head of circular doubly-linked list of all objects.  These are linked
  40  * together via the _ob_prev and _ob_next members of a PyObject, which
  41  * exist only in a Py_TRACE_REFS build.
  42  */
  43 static PyObject refchain = {&refchain, &refchain};
  44 
  45 /* Insert op at the front of the list of all objects.  If force is true,
  46  * op is added even if _ob_prev and _ob_next are non-NULL already.  If
  47  * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
  48  * force should be true if and only if op points to freshly allocated,
  49  * uninitialized memory, or you've unlinked op from the list and are
  50  * relinking it into the front.
  51  * Note that objects are normally added to the list via _Py_NewReference,
  52  * which is called by PyObject_Init.  Not all objects are initialized that
  53  * way, though; exceptions include statically allocated type objects, and
  54  * statically allocated singletons (like Py_True and Py_None).
  55  */
  56 void
  57 _Py_AddToAllObjects(PyObject *op, int force)
  58 {
  59 #ifdef  Py_DEBUG
  60     if (!force) {
  61         /* If it's initialized memory, op must be in or out of
  62          * the list unambiguously.
  63          */
  64         assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
  65     }
  66 #endif
  67     if (force || op->_ob_prev == NULL) {
  68         op->_ob_next = refchain._ob_next;
  69         op->_ob_prev = &refchain;
  70         refchain._ob_next->_ob_prev = op;
  71         refchain._ob_next = op;
  72     }
  73 }
  74 #endif  /* Py_TRACE_REFS */
  75 
  76 #ifdef COUNT_ALLOCS
  77 static PyTypeObject *type_list;
  78 /* All types are added to type_list, at least when
  79    they get one object created. That makes them
  80    immortal, which unfortunately contributes to
  81    garbage itself. If unlist_types_without_objects
  82    is set, they will be removed from the type_list
  83    once the last object is deallocated. */
  84 static int unlist_types_without_objects;
  85 extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
  86 extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
  87 extern Py_ssize_t null_strings, one_strings;
  88 void
  89 dump_counts(FILE* f)
  90 {
  91     PyTypeObject *tp;
  92 
  93     for (tp = type_list; tp; tp = tp->tp_next)
  94         fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
  95             "freed: %" PY_FORMAT_SIZE_T "d, "
  96             "max in use: %" PY_FORMAT_SIZE_T "d\n",
  97             tp->tp_name, tp->tp_allocs, tp->tp_frees,
  98             tp->tp_maxalloc);
  99     fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
 100         "empty: %" PY_FORMAT_SIZE_T "d\n",
 101         fast_tuple_allocs, tuple_zero_allocs);
 102     fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
 103         "neg: %" PY_FORMAT_SIZE_T "d\n",
 104         quick_int_allocs, quick_neg_int_allocs);
 105     fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
 106         "1-strings: %" PY_FORMAT_SIZE_T "d\n",
 107         null_strings, one_strings);
 108 }
 109 
 110 PyObject *
 111 get_counts(void)
 112 {
 113     PyTypeObject *tp;
 114     PyObject *result;
 115     PyObject *v;
 116 
 117     result = PyList_New(0);
 118     if (result == NULL)
 119         return NULL;
 120     for (tp = type_list; tp; tp = tp->tp_next) {
 121         v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
 122                           tp->tp_frees, tp->tp_maxalloc);
 123         if (v == NULL) {
 124             Py_DECREF(result);
 125             return NULL;
 126         }
 127         if (PyList_Append(result, v) < 0) {
 128             Py_DECREF(v);
 129             Py_DECREF(result);
 130             return NULL;
 131         }
 132         Py_DECREF(v);
 133     }
 134     return result;
 135 }
 136 
 137 void
 138 inc_count(PyTypeObject *tp)
 139 {
 140     if (tp->tp_next == NULL && tp->tp_prev == NULL) {
 141         /* first time; insert in linked list */
 142         if (tp->tp_next != NULL) /* sanity check */
 143             Py_FatalError("XXX inc_count sanity check");
 144         if (type_list)
 145             type_list->tp_prev = tp;
 146         tp->tp_next = type_list;
 147         /* Note that as of Python 2.2, heap-allocated type objects
 148          * can go away, but this code requires that they stay alive
 149          * until program exit.  That's why we're careful with
 150          * refcounts here.  type_list gets a new reference to tp,
 151          * while ownership of the reference type_list used to hold
 152          * (if any) was transferred to tp->tp_next in the line above.
 153          * tp is thus effectively immortal after this.
 154          */
 155         Py_INCREF(tp);
 156         type_list = tp;
 157 #ifdef Py_TRACE_REFS
 158         /* Also insert in the doubly-linked list of all objects,
 159          * if not already there.
 160          */
 161         _Py_AddToAllObjects((PyObject *)tp, 0);
 162 #endif
 163     }
 164     tp->tp_allocs++;
 165     if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
 166         tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
 167 }
 168 
 169 void dec_count(PyTypeObject *tp)
 170 {
 171     tp->tp_frees++;
 172     if (unlist_types_without_objects &&
 173         tp->tp_allocs == tp->tp_frees) {
 174         /* unlink the type from type_list */
 175         if (tp->tp_prev)
 176             tp->tp_prev->tp_next = tp->tp_next;
 177         else
 178             type_list = tp->tp_next;
 179         if (tp->tp_next)
 180             tp->tp_next->tp_prev = tp->tp_prev;
 181         tp->tp_next = tp->tp_prev = NULL;
 182         Py_DECREF(tp);
 183     }
 184 }
 185 
 186 #endif
 187 
 188 #ifdef Py_REF_DEBUG
 189 /* Log a fatal error; doesn't return. */
 190 void
 191 _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
 192 {
 193     char buf[300];
 194 
 195     PyOS_snprintf(buf, sizeof(buf),
 196                   "%s:%i object at %p has negative ref count "
 197                   "%" PY_FORMAT_SIZE_T "d",
 198                   fname, lineno, op, op->ob_refcnt);
 199     Py_FatalError(buf);
 200 }
 201 
 202 #endif /* Py_REF_DEBUG */
 203 
 204 void
 205 Py_IncRef(PyObject *o)
 206 {
 207     Py_XINCREF(o);
 208 }
 209 
 210 void
 211 Py_DecRef(PyObject *o)
 212 {
 213     Py_XDECREF(o);
 214 }
 215 
 216 PyObject *
 217 PyObject_Init(PyObject *op, PyTypeObject *tp)
 218 {
 219     if (op == NULL)
 220         return PyErr_NoMemory();
 221     /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
 222     Py_TYPE(op) = tp;
 223     _Py_NewReference(op);
 224     return op;
 225 }
 226 
 227 PyVarObject *
 228 PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
 229 {
 230     if (op == NULL)
 231         return (PyVarObject *) PyErr_NoMemory();
 232     /* Any changes should be reflected in PyObject_INIT_VAR */
 233     op->ob_size = size;
 234     Py_TYPE(op) = tp;
 235     _Py_NewReference((PyObject *)op);
 236     return op;
 237 }
 238 
 239 PyObject *
 240 _PyObject_New(PyTypeObject *tp)
 241 {
 242     PyObject *op;
 243     op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
 244     if (op == NULL)
 245         return PyErr_NoMemory();
 246     return PyObject_INIT(op, tp);
 247 }
 248 
 249 PyVarObject *
 250 _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
 251 {
 252     PyVarObject *op;
 253     const size_t size = _PyObject_VAR_SIZE(tp, nitems);
 254     op = (PyVarObject *) PyObject_MALLOC(size);
 255     if (op == NULL)
 256         return (PyVarObject *)PyErr_NoMemory();
 257     return PyObject_INIT_VAR(op, tp, nitems);
 258 }
 259 
 260 /* for binary compatibility with 2.2 */
 261 #undef _PyObject_Del
 262 void
 263 _PyObject_Del(PyObject *op)
 264 {
 265     PyObject_FREE(op);
 266 }
 267 
 268 /* Implementation of PyObject_Print with recursion checking */
 269 static int
 270 internal_print(PyObject *op, FILE *fp, int flags, int nesting)
 271 {
 272     int ret = 0;
 273     if (nesting > 10) {
 274         PyErr_SetString(PyExc_RuntimeError, "print recursion");
 275         return -1;
 276     }
 277     if (PyErr_CheckSignals())
 278         return -1;
 279 #ifdef USE_STACKCHECK
 280     if (PyOS_CheckStack()) {
 281         PyErr_SetString(PyExc_MemoryError, "stack overflow");
 282         return -1;
 283     }
 284 #endif
 285     clearerr(fp); /* Clear any previous error condition */
 286     if (op == NULL) {
 287         Py_BEGIN_ALLOW_THREADS
 288         fprintf(fp, "<nil>");
 289         Py_END_ALLOW_THREADS
 290     }
 291     else {
 292         if (op->ob_refcnt <= 0)
 293             /* XXX(twouters) cast refcount to long until %zd is
 294                universally available */
 295             Py_BEGIN_ALLOW_THREADS
 296             fprintf(fp, "<refcnt %ld at %p>",
 297                 (long)op->ob_refcnt, op);
 298             Py_END_ALLOW_THREADS
 299         else if (Py_TYPE(op)->tp_print == NULL) {
 300             PyObject *s;
 301             if (flags & Py_PRINT_RAW)
 302                 s = PyObject_Str(op);
 303             else
 304                 s = PyObject_Repr(op);
 305             if (s == NULL)
 306                 ret = -1;
 307             else {
 308                 ret = internal_print(s, fp, Py_PRINT_RAW,
 309                                      nesting+1);
 310             }
 311             Py_XDECREF(s);
 312         }
 313         else
 314             ret = (*Py_TYPE(op)->tp_print)(op, fp, flags);
 315     }
 316     if (ret == 0) {
 317         if (ferror(fp)) {
 318             PyErr_SetFromErrno(PyExc_IOError);
 319             clearerr(fp);
 320             ret = -1;
 321         }
 322     }
 323     return ret;
 324 }
 325 
 326 int
 327 PyObject_Print(PyObject *op, FILE *fp, int flags)
 328 {
 329     return internal_print(op, fp, flags, 0);
 330 }
 331 
 332 
 333 /* For debugging convenience.  See Misc/gdbinit for some useful gdb hooks */
 334 void _PyObject_Dump(PyObject* op)
 335 {
 336     if (op == NULL)
 337         fprintf(stderr, "NULL\n");
 338     else {
 339 #ifdef WITH_THREAD
 340         PyGILState_STATE gil;
 341 #endif
 342         fprintf(stderr, "object  : ");
 343 #ifdef WITH_THREAD
 344         gil = PyGILState_Ensure();
 345 #endif
 346         (void)PyObject_Print(op, stderr, 0);
 347 #ifdef WITH_THREAD
 348         PyGILState_Release(gil);
 349 #endif
 350         /* XXX(twouters) cast refcount to long until %zd is
 351            universally available */
 352         fprintf(stderr, "\n"
 353             "type    : %s\n"
 354             "refcount: %ld\n"
 355             "address : %p\n",
 356             Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
 357             (long)op->ob_refcnt,
 358             op);
 359     }
 360 }
 361 
 362 PyObject *
 363 PyObject_Repr(PyObject *v)
 364 {
 365     if (PyErr_CheckSignals())
 366         return NULL;
 367 #ifdef USE_STACKCHECK
 368     if (PyOS_CheckStack()) {
 369         PyErr_SetString(PyExc_MemoryError, "stack overflow");
 370         return NULL;
 371     }
 372 #endif
 373     if (v == NULL)
 374         return PyString_FromString("<NULL>");
 375     else if (Py_TYPE(v)->tp_repr == NULL)
 376         return PyString_FromFormat("<%s object at %p>",
 377                                    Py_TYPE(v)->tp_name, v);
 378     else {
 379         PyObject *res;
 380         res = (*Py_TYPE(v)->tp_repr)(v);
 381         if (res == NULL)
 382             return NULL;
 383 #ifdef Py_USING_UNICODE
 384         if (PyUnicode_Check(res)) {
 385             PyObject* str;
 386             str = PyUnicode_AsEncodedString(res, NULL, NULL);
 387             Py_DECREF(res);
 388             if (str)
 389                 res = str;
 390             else
 391                 return NULL;
 392         }
 393 #endif
 394         if (!PyString_Check(res)) {
 395             PyErr_Format(PyExc_TypeError,
 396                          "__repr__ returned non-string (type %.200s)",
 397                          Py_TYPE(res)->tp_name);
 398             Py_DECREF(res);
 399             return NULL;
 400         }
 401         return res;
 402     }
 403 }
 404 
 405 PyObject *
 406 _PyObject_Str(PyObject *v)
 407 {
 408     PyObject *res;
 409     int type_ok;
 410     if (v == NULL)
 411         return PyString_FromString("<NULL>");
 412     if (PyString_CheckExact(v)) {
 413         Py_INCREF(v);
 414         return v;
 415     }
 416 #ifdef Py_USING_UNICODE
 417     if (PyUnicode_CheckExact(v)) {
 418         Py_INCREF(v);
 419         return v;
 420     }
 421 #endif
 422     if (Py_TYPE(v)->tp_str == NULL)
 423         return PyObject_Repr(v);
 424 
 425     /* It is possible for a type to have a tp_str representation that loops
 426        infinitely. */
 427     if (Py_EnterRecursiveCall(" while getting the str of an object"))
 428         return NULL;
 429     res = (*Py_TYPE(v)->tp_str)(v);
 430     Py_LeaveRecursiveCall();
 431     if (res == NULL)
 432         return NULL;
 433     type_ok = PyString_Check(res);
 434 #ifdef Py_USING_UNICODE
 435     type_ok = type_ok || PyUnicode_Check(res);
 436 #endif
 437     if (!type_ok) {
 438         PyErr_Format(PyExc_TypeError,
 439                      "__str__ returned non-string (type %.200s)",
 440                      Py_TYPE(res)->tp_name);
 441         Py_DECREF(res);
 442         return NULL;
 443     }
 444     return res;
 445 }
 446 
 447 PyObject *
 448 PyObject_Str(PyObject *v)
 449 {
 450     PyObject *res = _PyObject_Str(v);
 451     if (res == NULL)
 452         return NULL;
 453 #ifdef Py_USING_UNICODE
 454     if (PyUnicode_Check(res)) {
 455         PyObject* str;
 456         str = PyUnicode_AsEncodedString(res, NULL, NULL);
 457         Py_DECREF(res);
 458         if (str)
 459             res = str;
 460         else
 461             return NULL;
 462     }
 463 #endif
 464     assert(PyString_Check(res));
 465     return res;
 466 }
 467 
 468 #ifdef Py_USING_UNICODE
 469 PyObject *
 470 PyObject_Unicode(PyObject *v)
 471 {
 472     PyObject *res;
 473     PyObject *func;
 474     PyObject *str;
 475     int unicode_method_found = 0;
 476     static PyObject *unicodestr;
 477 
 478     if (v == NULL) {
 479         res = PyString_FromString("<NULL>");
 480         if (res == NULL)
 481             return NULL;
 482         str = PyUnicode_FromEncodedObject(res, NULL, "strict");
 483         Py_DECREF(res);
 484         return str;
 485     } else if (PyUnicode_CheckExact(v)) {
 486         Py_INCREF(v);
 487         return v;
 488     }
 489 
 490     if (PyInstance_Check(v)) {
 491         /* We're an instance of a classic class */
 492         /* Try __unicode__ from the instance -- alas we have no type */
 493         func = PyObject_GetAttr(v, unicodestr);
 494         if (func != NULL) {
 495             unicode_method_found = 1;
 496             res = PyObject_CallFunctionObjArgs(func, NULL);
 497             Py_DECREF(func);
 498         }
 499         else {
 500             PyErr_Clear();
 501         }
 502     }
 503     else {
 504         /* Not a classic class instance, try __unicode__. */
 505         func = _PyObject_LookupSpecial(v, "__unicode__", &unicodestr);
 506         if (func != NULL) {
 507             unicode_method_found = 1;
 508             res = PyObject_CallFunctionObjArgs(func, NULL);
 509             Py_DECREF(func);
 510         }
 511         else if (PyErr_Occurred())
 512             return NULL;
 513     }
 514 
 515     /* Didn't find __unicode__ */
 516     if (!unicode_method_found) {
 517         if (PyUnicode_Check(v)) {
 518             /* For a Unicode subtype that's didn't overwrite __unicode__,
 519                return a true Unicode object with the same data. */
 520             return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
 521                                          PyUnicode_GET_SIZE(v));
 522         }
 523         if (PyString_CheckExact(v)) {
 524             Py_INCREF(v);
 525             res = v;
 526         }
 527         else {
 528             if (Py_TYPE(v)->tp_str != NULL)
 529                 res = (*Py_TYPE(v)->tp_str)(v);
 530             else
 531                 res = PyObject_Repr(v);
 532         }
 533     }
 534 
 535     if (res == NULL)
 536         return NULL;
 537     if (!PyUnicode_Check(res)) {
 538         str = PyUnicode_FromEncodedObject(res, NULL, "strict");
 539         Py_DECREF(res);
 540         res = str;
 541     }
 542     return res;
 543 }
 544 #endif
 545 
 546 
 547 /* Helper to warn about deprecated tp_compare return values.  Return:
 548    -2 for an exception;
 549    -1 if v <  w;
 550     0 if v == w;
 551     1 if v  > w.
 552    (This function cannot return 2.)
 553 */
 554 static int
 555 adjust_tp_compare(int c)
 556 {
 557     if (PyErr_Occurred()) {
 558         if (c != -1 && c != -2) {
 559             PyObject *t, *v, *tb;
 560             PyErr_Fetch(&t, &v, &tb);
 561             if (PyErr_Warn(PyExc_RuntimeWarning,
 562                            "tp_compare didn't return -1 or -2 "
 563                            "for exception") < 0) {
 564                 Py_XDECREF(t);
 565                 Py_XDECREF(v);
 566                 Py_XDECREF(tb);
 567             }
 568             else
 569                 PyErr_Restore(t, v, tb);
 570         }
 571         return -2;
 572     }
 573     else if (c < -1 || c > 1) {
 574         if (PyErr_Warn(PyExc_RuntimeWarning,
 575                        "tp_compare didn't return -1, 0 or 1") < 0)
 576             return -2;
 577         else
 578             return c < -1 ? -1 : 1;
 579     }
 580     else {
 581         assert(c >= -1 && c <= 1);
 582         return c;
 583     }
 584 }
 585 
 586 
 587 /* Macro to get the tp_richcompare field of a type if defined */
 588 #define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
 589              ? (t)->tp_richcompare : NULL)
 590 
 591 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
 592 int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
 593 
 594 /* Try a genuine rich comparison, returning an object.  Return:
 595    NULL for exception;
 596    NotImplemented if this particular rich comparison is not implemented or
 597      undefined;
 598    some object not equal to NotImplemented if it is implemented
 599      (this latter object may not be a Boolean).
 600 */
 601 static PyObject *
 602 try_rich_compare(PyObject *v, PyObject *w, int op)
 603 {
 604     richcmpfunc f;
 605     PyObject *res;
 606 
 607     if (v->ob_type != w->ob_type &&
 608         PyType_IsSubtype(w->ob_type, v->ob_type) &&
 609         (f = RICHCOMPARE(w->ob_type)) != NULL) {
 610         res = (*f)(w, v, _Py_SwappedOp[op]);
 611         if (res != Py_NotImplemented)
 612             return res;
 613         Py_DECREF(res);
 614     }
 615     if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
 616         res = (*f)(v, w, op);
 617         if (res != Py_NotImplemented)
 618             return res;
 619         Py_DECREF(res);
 620     }
 621     if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
 622         return (*f)(w, v, _Py_SwappedOp[op]);
 623     }
 624     res = Py_NotImplemented;
 625     Py_INCREF(res);
 626     return res;
 627 }
 628 
 629 /* Try a genuine rich comparison, returning an int.  Return:
 630    -1 for exception (including the case where try_rich_compare() returns an
 631       object that's not a Boolean);
 632     0 if the outcome is false;
 633     1 if the outcome is true;
 634     2 if this particular rich comparison is not implemented or undefined.
 635 */
 636 static int
 637 try_rich_compare_bool(PyObject *v, PyObject *w, int op)
 638 {
 639     PyObject *res;
 640     int ok;
 641 
 642     if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
 643         return 2; /* Shortcut, avoid INCREF+DECREF */
 644     res = try_rich_compare(v, w, op);
 645     if (res == NULL)
 646         return -1;
 647     if (res == Py_NotImplemented) {
 648         Py_DECREF(res);
 649         return 2;
 650     }
 651     ok = PyObject_IsTrue(res);
 652     Py_DECREF(res);
 653     return ok;
 654 }
 655 
 656 /* Try rich comparisons to determine a 3-way comparison.  Return:
 657    -2 for an exception;
 658    -1 if v  < w;
 659     0 if v == w;
 660     1 if v  > w;
 661     2 if this particular rich comparison is not implemented or undefined.
 662 */
 663 static int
 664 try_rich_to_3way_compare(PyObject *v, PyObject *w)
 665 {
 666     static struct { int op; int outcome; } tries[3] = {
 667         /* Try this operator, and if it is true, use this outcome: */
 668         {Py_EQ, 0},
 669         {Py_LT, -1},
 670         {Py_GT, 1},
 671     };
 672     int i;
 673 
 674     if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
 675         return 2; /* Shortcut */
 676 
 677     for (i = 0; i < 3; i++) {
 678         switch (try_rich_compare_bool(v, w, tries[i].op)) {
 679         case -1:
 680             return -2;
 681         case 1:
 682             return tries[i].outcome;
 683         }
 684     }
 685 
 686     return 2;
 687 }
 688 
 689 /* Try a 3-way comparison, returning an int.  Return:
 690    -2 for an exception;
 691    -1 if v <  w;
 692     0 if v == w;
 693     1 if v  > w;
 694     2 if this particular 3-way comparison is not implemented or undefined.
 695 */
 696 static int
 697 try_3way_compare(PyObject *v, PyObject *w)
 698 {
 699     int c;
 700     cmpfunc f;
 701 
 702     /* Comparisons involving instances are given to instance_compare,
 703        which has the same return conventions as this function. */
 704 
 705     f = v->ob_type->tp_compare;
 706     if (PyInstance_Check(v))
 707         return (*f)(v, w);
 708     if (PyInstance_Check(w))
 709         return (*w->ob_type->tp_compare)(v, w);
 710 
 711     /* If both have the same (non-NULL) tp_compare, use it. */
 712     if (f != NULL && f == w->ob_type->tp_compare) {
 713         c = (*f)(v, w);
 714         return adjust_tp_compare(c);
 715     }
 716 
 717     /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
 718     if (f == _PyObject_SlotCompare ||
 719         w->ob_type->tp_compare == _PyObject_SlotCompare)
 720         return _PyObject_SlotCompare(v, w);
 721 
 722     /* If we're here, v and w,
 723         a) are not instances;
 724         b) have different types or a type without tp_compare; and
 725         c) don't have a user-defined tp_compare.
 726        tp_compare implementations in C assume that both arguments
 727        have their type, so we give up if the coercion fails or if
 728        it yields types which are still incompatible (which can
 729        happen with a user-defined nb_coerce).
 730     */
 731     c = PyNumber_CoerceEx(&v, &w);
 732     if (c < 0)
 733         return -2;
 734     if (c > 0)
 735         return 2;
 736     f = v->ob_type->tp_compare;
 737     if (f != NULL && f == w->ob_type->tp_compare) {
 738         c = (*f)(v, w);
 739         Py_DECREF(v);
 740         Py_DECREF(w);
 741         return adjust_tp_compare(c);
 742     }
 743 
 744     /* No comparison defined */
 745     Py_DECREF(v);
 746     Py_DECREF(w);
 747     return 2;
 748 }
 749 
 750 /* Final fallback 3-way comparison, returning an int.  Return:
 751    -2 if an error occurred;
 752    -1 if v <  w;
 753     0 if v == w;
 754     1 if v >  w.
 755 */
 756 static int
 757 default_3way_compare(PyObject *v, PyObject *w)
 758 {
 759     int c;
 760     const char *vname, *wname;
 761 
 762     if (v->ob_type == w->ob_type) {
 763         /* When comparing these pointers, they must be cast to
 764          * integer types (i.e. Py_uintptr_t, our spelling of C9X's
 765          * uintptr_t).  ANSI specifies that pointer compares other
 766          * than == and != to non-related structures are undefined.
 767          */
 768         Py_uintptr_t vv = (Py_uintptr_t)v;
 769         Py_uintptr_t ww = (Py_uintptr_t)w;
 770         return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
 771     }
 772 
 773     /* None is smaller than anything */
 774     if (v == Py_None)
 775         return -1;
 776     if (w == Py_None)
 777         return 1;
 778 
 779     /* different type: compare type names; numbers are smaller */
 780     if (PyNumber_Check(v))
 781         vname = "";
 782     else
 783         vname = v->ob_type->tp_name;
 784     if (PyNumber_Check(w))
 785         wname = "";
 786     else
 787         wname = w->ob_type->tp_name;
 788     c = strcmp(vname, wname);
 789     if (c < 0)
 790         return -1;
 791     if (c > 0)
 792         return 1;
 793     /* Same type name, or (more likely) incomparable numeric types */
 794     return ((Py_uintptr_t)(v->ob_type) < (
 795         Py_uintptr_t)(w->ob_type)) ? -1 : 1;
 796 }
 797 
 798 /* Do a 3-way comparison, by hook or by crook.  Return:
 799    -2 for an exception (but see below);
 800    -1 if v <  w;
 801     0 if v == w;
 802     1 if v >  w;
 803    BUT: if the object implements a tp_compare function, it returns
 804    whatever this function returns (whether with an exception or not).
 805 */
 806 static int
 807 do_cmp(PyObject *v, PyObject *w)
 808 {
 809     int c;
 810     cmpfunc f;
 811 
 812     if (v->ob_type == w->ob_type
 813         && (f = v->ob_type->tp_compare) != NULL) {
 814         c = (*f)(v, w);
 815         if (PyInstance_Check(v)) {
 816             /* Instance tp_compare has a different signature.
 817                But if it returns undefined we fall through. */
 818             if (c != 2)
 819                 return c;
 820             /* Else fall through to try_rich_to_3way_compare() */
 821         }
 822         else
 823             return adjust_tp_compare(c);
 824     }
 825     /* We only get here if one of the following is true:
 826        a) v and w have different types
 827        b) v and w have the same type, which doesn't have tp_compare
 828        c) v and w are instances, and either __cmp__ is not defined or
 829           __cmp__ returns NotImplemented
 830     */
 831     c = try_rich_to_3way_compare(v, w);
 832     if (c < 2)
 833         return c;
 834     c = try_3way_compare(v, w);
 835     if (c < 2)
 836         return c;
 837     return default_3way_compare(v, w);
 838 }
 839 
 840 /* Compare v to w.  Return
 841    -1 if v <  w or exception (PyErr_Occurred() true in latter case).
 842     0 if v == w.
 843     1 if v > w.
 844    XXX The docs (C API manual) say the return value is undefined in case
 845    XXX of error.
 846 */
 847 int
 848 PyObject_Compare(PyObject *v, PyObject *w)
 849 {
 850     int result;
 851 
 852     if (v == NULL || w == NULL) {
 853         PyErr_BadInternalCall();
 854         return -1;
 855     }
 856     if (v == w)
 857         return 0;
 858     if (Py_EnterRecursiveCall(" in cmp"))
 859         return -1;
 860     result = do_cmp(v, w);
 861     Py_LeaveRecursiveCall();
 862     return result < 0 ? -1 : result;
 863 }
 864 
 865 /* Return (new reference to) Py_True or Py_False. */
 866 static PyObject *
 867 convert_3way_to_object(int op, int c)
 868 {
 869     PyObject *result;
 870     switch (op) {
 871     case Py_LT: c = c <  0; break;
 872     case Py_LE: c = c <= 0; break;
 873     case Py_EQ: c = c == 0; break;
 874     case Py_NE: c = c != 0; break;
 875     case Py_GT: c = c >  0; break;
 876     case Py_GE: c = c >= 0; break;
 877     }
 878     result = c ? Py_True : Py_False;
 879     Py_INCREF(result);
 880     return result;
 881 }
 882 
 883 /* We want a rich comparison but don't have one.  Try a 3-way cmp instead.
 884    Return
 885    NULL      if error
 886    Py_True   if v op w
 887    Py_False  if not (v op w)
 888 */
 889 static PyObject *
 890 try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
 891 {
 892     int c;
 893 
 894     c = try_3way_compare(v, w);
 895     if (c >= 2) {
 896 
 897         /* Py3K warning if types are not equal and comparison isn't == or !=  */
 898         if (Py_Py3kWarningFlag &&
 899             v->ob_type != w->ob_type && op != Py_EQ && op != Py_NE &&
 900             PyErr_WarnEx(PyExc_DeprecationWarning,
 901                        "comparing unequal types not supported "
 902                        "in 3.x", 1) < 0) {
 903             return NULL;
 904         }
 905 
 906         c = default_3way_compare(v, w);
 907     }
 908     if (c <= -2)
 909         return NULL;
 910     return convert_3way_to_object(op, c);
 911 }
 912 
 913 /* Do rich comparison on v and w.  Return
 914    NULL      if error
 915    Else a new reference to an object other than Py_NotImplemented, usually(?):
 916    Py_True   if v op w
 917    Py_False  if not (v op w)
 918 */
 919 static PyObject *
 920 do_richcmp(PyObject *v, PyObject *w, int op)
 921 {
 922     PyObject *res;
 923 
 924     res = try_rich_compare(v, w, op);
 925     if (res != Py_NotImplemented)
 926         return res;
 927     Py_DECREF(res);
 928 
 929     return try_3way_to_rich_compare(v, w, op);
 930 }
 931 
 932 /* Return:
 933    NULL for exception;
 934    some object not equal to NotImplemented if it is implemented
 935      (this latter object may not be a Boolean).
 936 */
 937 PyObject *
 938 PyObject_RichCompare(PyObject *v, PyObject *w, int op)
 939 {
 940     PyObject *res;
 941 
 942     assert(Py_LT <= op && op <= Py_GE);
 943     if (Py_EnterRecursiveCall(" in cmp"))
 944         return NULL;
 945 
 946     /* If the types are equal, and not old-style instances, try to
 947        get out cheap (don't bother with coercions etc.). */
 948     if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
 949         cmpfunc fcmp;
 950         richcmpfunc frich = RICHCOMPARE(v->ob_type);
 951         /* If the type has richcmp, try it first.  try_rich_compare
 952            tries it two-sided, which is not needed since we've a
 953            single type only. */
 954         if (frich != NULL) {
 955             res = (*frich)(v, w, op);
 956             if (res != Py_NotImplemented)
 957                 goto Done;
 958             Py_DECREF(res);
 959         }
 960         /* No richcmp, or this particular richmp not implemented.
 961            Try 3-way cmp. */
 962         fcmp = v->ob_type->tp_compare;
 963         if (fcmp != NULL) {
 964             int c = (*fcmp)(v, w);
 965             c = adjust_tp_compare(c);
 966             if (c == -2) {
 967                 res = NULL;
 968                 goto Done;
 969             }
 970             res = convert_3way_to_object(op, c);
 971             goto Done;
 972         }
 973     }
 974 
 975     /* Fast path not taken, or couldn't deliver a useful result. */
 976     res = do_richcmp(v, w, op);
 977 Done:
 978     Py_LeaveRecursiveCall();
 979     return res;
 980 }
 981 
 982 /* Return -1 if error; 1 if v op w; 0 if not (v op w). */
 983 int
 984 PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
 985 {
 986     PyObject *res;
 987     int ok;
 988 
 989     /* Quick result when objects are the same.
 990        Guarantees that identity implies equality. */
 991     if (v == w) {
 992         if (op == Py_EQ)
 993             return 1;
 994         else if (op == Py_NE)
 995             return 0;
 996     }
 997 
 998     res = PyObject_RichCompare(v, w, op);
 999     if (res == NULL)
1000         return -1;
1001     if (PyBool_Check(res))
1002         ok = (res == Py_True);
1003     else
1004         ok = PyObject_IsTrue(res);
1005     Py_DECREF(res);
1006     return ok;
1007 }
1008 
1009 /* Set of hash utility functions to help maintaining the invariant that
1010     if a==b then hash(a)==hash(b)
1011 
1012    All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1013 */
1014 
1015 long
1016 _Py_HashDouble(double v)
1017 {
1018     double intpart, fractpart;
1019     int expo;
1020     long hipart;
1021     long x;             /* the final hash value */
1022     /* This is designed so that Python numbers of different types
1023      * that compare equal hash to the same value; otherwise comparisons
1024      * of mapping keys will turn out weird.
1025      */
1026 
1027     if (!Py_IS_FINITE(v)) {
1028         if (Py_IS_INFINITY(v))
1029             return v < 0 ? -271828 : 314159;
1030         else
1031             return 0;
1032     }
1033     fractpart = modf(v, &intpart);
1034     if (fractpart == 0.0) {
1035         /* This must return the same hash as an equal int or long. */
1036         if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) {
1037             /* Convert to long and use its hash. */
1038             PyObject *plong;                    /* converted to Python long */
1039             plong = PyLong_FromDouble(v);
1040             if (plong == NULL)
1041                 return -1;
1042             x = PyObject_Hash(plong);
1043             Py_DECREF(plong);
1044             return x;
1045         }
1046         /* Fits in a C long == a Python int, so is its own hash. */
1047         x = (long)intpart;
1048         if (x == -1)
1049             x = -2;
1050         return x;
1051     }
1052     /* The fractional part is non-zero, so we don't have to worry about
1053      * making this match the hash of some other type.
1054      * Use frexp to get at the bits in the double.
1055      * Since the VAX D double format has 56 mantissa bits, which is the
1056      * most of any double format in use, each of these parts may have as
1057      * many as (but no more than) 56 significant bits.
1058      * So, assuming sizeof(long) >= 4, each part can be broken into two
1059      * longs; frexp and multiplication are used to do that.
1060      * Also, since the Cray double format has 15 exponent bits, which is
1061      * the most of any double format in use, shifting the exponent field
1062      * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
1063      */
1064     v = frexp(v, &expo);
1065     v *= 2147483648.0;          /* 2**31 */
1066     hipart = (long)v;           /* take the top 32 bits */
1067     v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1068     x = hipart + (long)v + (expo << 15);
1069     if (x == -1)
1070         x = -2;
1071     return x;
1072 }
1073 
1074 long
1075 _Py_HashPointer(void *p)
1076 {
1077     long x;
1078     size_t y = (size_t)p;
1079     /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
1080        excessive hash collisions for dicts and sets */
1081     y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
1082     x = (long)y;
1083     if (x == -1)
1084         x = -2;
1085     return x;
1086 }
1087 
1088 long
1089 PyObject_HashNotImplemented(PyObject *self)
1090 {
1091     PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
1092                  self->ob_type->tp_name);
1093     return -1;
1094 }
1095 
1096 _Py_HashSecret_t _Py_HashSecret;
1097 
1098 long
1099 PyObject_Hash(PyObject *v)
1100 {
1101     PyTypeObject *tp = v->ob_type;
1102     if (tp->tp_hash != NULL)
1103         return (*tp->tp_hash)(v);
1104     /* To keep to the general practice that inheriting
1105      * solely from object in C code should work without
1106      * an explicit call to PyType_Ready, we implicitly call
1107      * PyType_Ready here and then check the tp_hash slot again
1108      */
1109     if (tp->tp_dict == NULL) {
1110         if (PyType_Ready(tp) < 0)
1111             return -1;
1112         if (tp->tp_hash != NULL)
1113             return (*tp->tp_hash)(v);
1114     }
1115     if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
1116         return _Py_HashPointer(v); /* Use address as hash value */
1117     }
1118     /* If there's a cmp but no hash defined, the object can't be hashed */
1119     return PyObject_HashNotImplemented(v);
1120 }
1121 
1122 PyObject *
1123 PyObject_GetAttrString(PyObject *v, const char *name)
1124 {
1125     PyObject *w, *res;
1126 
1127     if (Py_TYPE(v)->tp_getattr != NULL)
1128         return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1129     w = PyString_InternFromString(name);
1130     if (w == NULL)
1131         return NULL;
1132     res = PyObject_GetAttr(v, w);
1133     Py_XDECREF(w);
1134     return res;
1135 }
1136 
1137 int
1138 PyObject_HasAttrString(PyObject *v, const char *name)
1139 {
1140     PyObject *res = PyObject_GetAttrString(v, name);
1141     if (res != NULL) {
1142         Py_DECREF(res);
1143         return 1;
1144     }
1145     PyErr_Clear();
1146     return 0;
1147 }
1148 
1149 int
1150 PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
1151 {
1152     PyObject *s;
1153     int res;
1154 
1155     if (Py_TYPE(v)->tp_setattr != NULL)
1156         return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1157     s = PyString_InternFromString(name);
1158     if (s == NULL)
1159         return -1;
1160     res = PyObject_SetAttr(v, s, w);
1161     Py_XDECREF(s);
1162     return res;
1163 }
1164 
1165 PyObject *
1166 PyObject_GetAttr(PyObject *v, PyObject *name)
1167 {
1168     PyTypeObject *tp = Py_TYPE(v);
1169 
1170     if (!PyString_Check(name)) {
1171 #ifdef Py_USING_UNICODE
Access to field 'ob_type' results in a dereference of a null pointer (loaded from variable 'name')

Possibly related backtrace: ade1bb6f43a00ab7b8e364cea3fb04ad5f22d358 MatchResult(frame_number=1, dist=0)

Possibly related backtrace: 214e768a4e79526d088fd7618e378b020bd2220d MatchResult(frame_number=1, dist=0)

(emitted by clang-analyzer)

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

Access to field 'ob_type' results in a dereference of a null pointer (loaded from variable 'name')

Possibly related backtrace: ade1bb6f43a00ab7b8e364cea3fb04ad5f22d358 MatchResult(frame_number=1, dist=0)

Possibly related backtrace: 214e768a4e79526d088fd7618e378b020bd2220d MatchResult(frame_number=1, dist=0)

(emitted by clang-analyzer)

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

1172 /* The Unicode to string conversion is done here because the 1173 existing tp_getattro slots expect a string object as name 1174 and we wouldn't want to break those. */ 1175 if (PyUnicode_Check(name)) { 1176 name = _PyUnicode_AsDefaultEncodedString(name, NULL); 1177 if (name == NULL) 1178 return NULL; 1179 } 1180 else 1181 #endif 1182 { 1183 PyErr_Format(PyExc_TypeError, 1184 "attribute name must be string, not '%.200s'", 1185 Py_TYPE(name)->tp_name); 1186 return NULL; 1187 } 1188 } 1189 if (tp->tp_getattro != NULL) 1190 return (*tp->tp_getattro)(v, name); 1191 if (tp->tp_getattr != NULL) 1192 return (*tp->tp_getattr)(v, PyString_AS_STRING(name)); 1193 PyErr_Format(PyExc_AttributeError, 1194 "'%.50s' object has no attribute '%.400s'", 1195 tp->tp_name, PyString_AS_STRING(name)); 1196 return NULL; 1197 } 1198 1199 int 1200 PyObject_HasAttr(PyObject *v, PyObject *name) 1201 { 1202 PyObject *res = PyObject_GetAttr(v, name); 1203 if (res != NULL) { 1204 Py_DECREF(res); 1205 return 1; 1206 } 1207 PyErr_Clear(); 1208 return 0; 1209 } 1210 1211 int 1212 PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value) 1213 { 1214 PyTypeObject *tp = Py_TYPE(v); 1215 int err; 1216 1217 if (!PyString_Check(name)){ 1218 #ifdef Py_USING_UNICODE 1219 /* The Unicode to string conversion is done here because the 1220 existing tp_setattro slots expect a string object as name 1221 and we wouldn't want to break those. */ 1222 if (PyUnicode_Check(name)) { 1223 name = PyUnicode_AsEncodedString(name, NULL, NULL); 1224 if (name == NULL) 1225 return -1; 1226 } 1227 else 1228 #endif 1229 { 1230 PyErr_Format(PyExc_TypeError, 1231 "attribute name must be string, not '%.200s'", 1232 Py_TYPE(name)->tp_name); 1233 return -1; 1234 } 1235 } 1236 else 1237 Py_INCREF(name); 1238 1239 PyString_InternInPlace(&name); 1240 if (tp->tp_setattro != NULL) { 1241 err = (*tp->tp_setattro)(v, name, value); 1242 Py_DECREF(name); 1243 return err; 1244 } 1245 if (tp->tp_setattr != NULL) { 1246 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value); 1247 Py_DECREF(name); 1248 return err; 1249 } 1250 Py_DECREF(name); 1251 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) 1252 PyErr_Format(PyExc_TypeError, 1253 "'%.100s' object has no attributes " 1254 "(%s .%.100s)", 1255 tp->tp_name, 1256 value==NULL ? "del" : "assign to", 1257 PyString_AS_STRING(name)); 1258 else 1259 PyErr_Format(PyExc_TypeError, 1260 "'%.100s' object has only read-only attributes " 1261 "(%s .%.100s)", 1262 tp->tp_name, 1263 value==NULL ? "del" : "assign to", 1264 PyString_AS_STRING(name)); 1265 return -1; 1266 } 1267 1268 /* Helper to get a pointer to an object's __dict__ slot, if any */ 1269 1270 PyObject ** 1271 _PyObject_GetDictPtr(PyObject *obj) 1272 { 1273 Py_ssize_t dictoffset; 1274 PyTypeObject *tp = Py_TYPE(obj); 1275 1276 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS)) 1277 return NULL; 1278 dictoffset = tp->tp_dictoffset; 1279 if (dictoffset == 0) 1280 return NULL; 1281 if (dictoffset < 0) { 1282 Py_ssize_t tsize; 1283 size_t size; 1284 1285 tsize = ((PyVarObject *)obj)->ob_size; 1286 if (tsize < 0) 1287 tsize = -tsize; 1288 size = _PyObject_VAR_SIZE(tp, tsize); 1289 1290 dictoffset += (long)size; 1291 assert(dictoffset > 0); 1292 assert(dictoffset % SIZEOF_VOID_P == 0); 1293 } 1294 return (PyObject **) ((char *)obj + dictoffset); 1295 } 1296 1297 PyObject * 1298 PyObject_SelfIter(PyObject *obj) 1299 { 1300 Py_INCREF(obj); 1301 return obj; 1302 } 1303 1304 /* Helper used when the __next__ method is removed from a type: 1305 tp_iternext is never NULL and can be safely called without checking 1306 on every iteration. 1307 */ 1308 1309 PyObject * 1310 _PyObject_NextNotImplemented(PyObject *self) 1311 { 1312 PyErr_Format(PyExc_TypeError, 1313 "'%.200s' object is not iterable", 1314 Py_TYPE(self)->tp_name); 1315 return NULL; 1316 } 1317 1318 /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */ 1319 1320 PyObject * 1321 _PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict) 1322 { 1323 PyTypeObject *tp = Py_TYPE(obj); 1324 PyObject *descr = NULL; 1325 PyObject *res = NULL; 1326 descrgetfunc f; 1327 Py_ssize_t dictoffset; 1328 PyObject **dictptr; 1329 1330 if (!PyString_Check(name)){ 1331 #ifdef Py_USING_UNICODE 1332 /* The Unicode to string conversion is done here because the 1333 existing tp_setattro slots expect a string object as name 1334 and we wouldn't want to break those. */ 1335 if (PyUnicode_Check(name)) { 1336 name = PyUnicode_AsEncodedString(name, NULL, NULL); 1337 if (name == NULL) 1338 return NULL; 1339 } 1340 else 1341 #endif 1342 { 1343 PyErr_Format(PyExc_TypeError, 1344 "attribute name must be string, not '%.200s'", 1345 Py_TYPE(name)->tp_name); 1346 return NULL; 1347 } 1348 } 1349 else 1350 Py_INCREF(name); 1351 1352 if (tp->tp_dict == NULL) { 1353 if (PyType_Ready(tp) < 0) 1354 goto done; 1355 } 1356 1357 #if 0 /* XXX this is not quite _PyType_Lookup anymore */ 1358 /* Inline _PyType_Lookup */ 1359 { 1360 Py_ssize_t i, n; 1361 PyObject *mro, *base, *dict; 1362 1363 /* Look in tp_dict of types in MRO */ 1364 mro = tp->tp_mro; 1365 assert(mro != NULL); 1366 assert(PyTuple_Check(mro)); 1367 n = PyTuple_GET_SIZE(mro); 1368 for (i = 0; i < n; i++) { 1369 base = PyTuple_GET_ITEM(mro, i); 1370 if (PyClass_Check(base)) 1371 dict = ((PyClassObject *)base)->cl_dict; 1372 else { 1373 assert(PyType_Check(base)); 1374 dict = ((PyTypeObject *)base)->tp_dict; 1375 } 1376 assert(dict && PyDict_Check(dict)); 1377 descr = PyDict_GetItem(dict, name); 1378 if (descr != NULL) 1379 break; 1380 } 1381 } 1382 #else 1383 descr = _PyType_Lookup(tp, name); 1384 #endif 1385 1386 Py_XINCREF(descr); 1387 1388 f = NULL; 1389 if (descr != NULL && 1390 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) { 1391 f = descr->ob_type->tp_descr_get; 1392 if (f != NULL && PyDescr_IsData(descr)) { 1393 res = f(descr, obj, (PyObject *)obj->ob_type); 1394 Py_DECREF(descr); 1395 goto done; 1396 } 1397 } 1398 1399 if (dict == NULL) { 1400 /* Inline _PyObject_GetDictPtr */ 1401 dictoffset = tp->tp_dictoffset; 1402 if (dictoffset != 0) { 1403 if (dictoffset < 0) { 1404 Py_ssize_t tsize; 1405 size_t size; 1406 1407 tsize = ((PyVarObject *)obj)->ob_size; 1408 if (tsize < 0) 1409 tsize = -tsize; 1410 size = _PyObject_VAR_SIZE(tp, tsize); 1411 1412 dictoffset += (long)size; 1413 assert(dictoffset > 0); 1414 assert(dictoffset % SIZEOF_VOID_P == 0); 1415 } 1416 dictptr = (PyObject **) ((char *)obj + dictoffset); 1417 dict = *dictptr; 1418 } 1419 } 1420 if (dict != NULL) { 1421 Py_INCREF(dict); 1422 res = PyDict_GetItem(dict, name); 1423 if (res != NULL) { 1424 Py_INCREF(res); 1425 Py_XDECREF(descr); 1426 Py_DECREF(dict); 1427 goto done; 1428 } 1429 Py_DECREF(dict); 1430 } 1431 1432 if (f != NULL) { 1433 res = f(descr, obj, (PyObject *)Py_TYPE(obj)); 1434 Py_DECREF(descr); 1435 goto done; 1436 } 1437 1438 if (descr != NULL) { 1439 res = descr; 1440 /* descr was already increfed above */ 1441 goto done; 1442 } 1443 1444 PyErr_Format(PyExc_AttributeError, 1445 "'%.50s' object has no attribute '%.400s'", 1446 tp->tp_name, PyString_AS_STRING(name)); 1447 done: 1448 Py_DECREF(name); 1449 return res; 1450 } 1451 1452 PyObject * 1453 PyObject_GenericGetAttr(PyObject *obj, PyObject *name) 1454 { 1455 return _PyObject_GenericGetAttrWithDict(obj, name, NULL); 1456 } 1457 1458 int 1459 _PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name, 1460 PyObject *value, PyObject *dict) 1461 { 1462 PyTypeObject *tp = Py_TYPE(obj); 1463 PyObject *descr; 1464 descrsetfunc f; 1465 PyObject **dictptr; 1466 int res = -1; 1467 1468 if (!PyString_Check(name)){ 1469 #ifdef Py_USING_UNICODE 1470 /* The Unicode to string conversion is done here because the 1471 existing tp_setattro slots expect a string object as name 1472 and we wouldn't want to break those. */ 1473 if (PyUnicode_Check(name)) { 1474 name = PyUnicode_AsEncodedString(name, NULL, NULL); 1475 if (name == NULL) 1476 return -1; 1477 } 1478 else 1479 #endif 1480 { 1481 PyErr_Format(PyExc_TypeError, 1482 "attribute name must be string, not '%.200s'", 1483 Py_TYPE(name)->tp_name); 1484 return -1; 1485 } 1486 } 1487 else 1488 Py_INCREF(name); 1489 1490 if (tp->tp_dict == NULL) { 1491 if (PyType_Ready(tp) < 0) 1492 goto done; 1493 } 1494 1495 descr = _PyType_Lookup(tp, name); 1496 f = NULL; 1497 if (descr != NULL && 1498 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) { 1499 f = descr->ob_type->tp_descr_set; 1500 if (f != NULL && PyDescr_IsData(descr)) { 1501 res = f(descr, obj, value); 1502 goto done; 1503 } 1504 } 1505 1506 if (dict == NULL) { 1507 dictptr = _PyObject_GetDictPtr(obj); 1508 if (dictptr != NULL) { 1509 dict = *dictptr; 1510 if (dict == NULL && value != NULL) { 1511 dict = PyDict_New(); 1512 if (dict == NULL) 1513 goto done; 1514 *dictptr = dict; 1515 } 1516 } 1517 } 1518 if (dict != NULL) { 1519 Py_INCREF(dict); 1520 if (value == NULL) 1521 res = PyDict_DelItem(dict, name); 1522 else 1523 res = PyDict_SetItem(dict, name, value); 1524 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) 1525 PyErr_SetObject(PyExc_AttributeError, name); 1526 Py_DECREF(dict); 1527 goto done; 1528 } 1529 1530 if (f != NULL) { 1531 res = f(descr, obj, value); 1532 goto done; 1533 } 1534 1535 if (descr == NULL) { 1536 PyErr_Format(PyExc_AttributeError, 1537 "'%.100s' object has no attribute '%.200s'", 1538 tp->tp_name, PyString_AS_STRING(name)); 1539 goto done; 1540 } 1541 1542 PyErr_Format(PyExc_AttributeError, 1543 "'%.50s' object attribute '%.400s' is read-only", 1544 tp->tp_name, PyString_AS_STRING(name)); 1545 done: 1546 Py_DECREF(name); 1547 return res; 1548 } 1549 1550 int 1551 PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value) 1552 { 1553 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL); 1554 } 1555 1556 1557 /* Test a value used as condition, e.g., in a for or if statement. 1558 Return -1 if an error occurred */ 1559 1560 int 1561 PyObject_IsTrue(PyObject *v) 1562 { 1563 Py_ssize_t res; 1564 if (v == Py_True) 1565 return 1; 1566 if (v == Py_False) 1567 return 0; 1568 if (v == Py_None) 1569 return 0; 1570 else if (v->ob_type->tp_as_number != NULL && 1571 v->ob_type->tp_as_number->nb_nonzero != NULL) 1572 res = (*v->ob_type->tp_as_number->nb_nonzero)(v); 1573 else if (v->ob_type->tp_as_mapping != NULL && 1574 v->ob_type->tp_as_mapping->mp_length != NULL) 1575 res = (*v->ob_type->tp_as_mapping->mp_length)(v); 1576 else if (v->ob_type->tp_as_sequence != NULL && 1577 v->ob_type->tp_as_sequence->sq_length != NULL) 1578 res = (*v->ob_type->tp_as_sequence->sq_length)(v); 1579 else 1580 return 1; 1581 /* if it is negative, it should be either -1 or -2 */ 1582 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); 1583 } 1584 1585 /* equivalent of 'not v' 1586 Return -1 if an error occurred */ 1587 1588 int 1589 PyObject_Not(PyObject *v) 1590 { 1591 int res; 1592 res = PyObject_IsTrue(v); 1593 if (res < 0) 1594 return res; 1595 return res == 0; 1596 } 1597 1598 /* Coerce two numeric types to the "larger" one. 1599 Increment the reference count on each argument. 1600 Return value: 1601 -1 if an error occurred; 1602 0 if the coercion succeeded (and then the reference counts are increased); 1603 1 if no coercion is possible (and no error is raised). 1604 */ 1605 int 1606 PyNumber_CoerceEx(PyObject **pv, PyObject **pw) 1607 { 1608 register PyObject *v = *pv; 1609 register PyObject *w = *pw; 1610 int res; 1611 1612 /* Shortcut only for old-style types */ 1613 if (v->ob_type == w->ob_type && 1614 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES)) 1615 { 1616 Py_INCREF(v); 1617 Py_INCREF(w); 1618 return 0; 1619 } 1620 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) { 1621 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw); 1622 if (res <= 0) 1623 return res; 1624 } 1625 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) { 1626 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv); 1627 if (res <= 0) 1628 return res; 1629 } 1630 return 1; 1631 } 1632 1633 /* Coerce two numeric types to the "larger" one. 1634 Increment the reference count on each argument. 1635 Return -1 and raise an exception if no coercion is possible 1636 (and then no reference count is incremented). 1637 */ 1638 int 1639 PyNumber_Coerce(PyObject **pv, PyObject **pw) 1640 { 1641 int err = PyNumber_CoerceEx(pv, pw); 1642 if (err <= 0) 1643 return err; 1644 PyErr_SetString(PyExc_TypeError, "number coercion failed"); 1645 return -1; 1646 } 1647 1648 1649 /* Test whether an object can be called */ 1650 1651 int 1652 PyCallable_Check(PyObject *x) 1653 { 1654 if (x == NULL) 1655 return 0; 1656 if (PyInstance_Check(x)) { 1657 PyObject *call = PyObject_GetAttrString(x, "__call__"); 1658 if (call == NULL) { 1659 PyErr_Clear(); 1660 return 0; 1661 } 1662 /* Could test recursively but don't, for fear of endless 1663 recursion if some joker sets self.__call__ = self */ 1664 Py_DECREF(call); 1665 return 1; 1666 } 1667 else { 1668 return x->ob_type->tp_call != NULL; 1669 } 1670 } 1671 1672 /* ------------------------- PyObject_Dir() helpers ------------------------- */ 1673 1674 /* Helper for PyObject_Dir. 1675 Merge the __dict__ of aclass into dict, and recursively also all 1676 the __dict__s of aclass's base classes. The order of merging isn't 1677 defined, as it's expected that only the final set of dict keys is 1678 interesting. 1679 Return 0 on success, -1 on error. 1680 */ 1681 1682 static int 1683 merge_class_dict(PyObject* dict, PyObject* aclass) 1684 { 1685 PyObject *classdict; 1686 PyObject *bases; 1687 1688 assert(PyDict_Check(dict)); 1689 assert(aclass); 1690 1691 /* Merge in the type's dict (if any). */ 1692 classdict = PyObject_GetAttrString(aclass, "__dict__"); 1693 if (classdict == NULL) 1694 PyErr_Clear(); 1695 else { 1696 int status = PyDict_Update(dict, classdict); 1697 Py_DECREF(classdict); 1698 if (status < 0) 1699 return -1; 1700 } 1701 1702 /* Recursively merge in the base types' (if any) dicts. */ 1703 bases = PyObject_GetAttrString(aclass, "__bases__"); 1704 if (bases == NULL) 1705 PyErr_Clear(); 1706 else { 1707 /* We have no guarantee that bases is a real tuple */ 1708 Py_ssize_t i, n; 1709 n = PySequence_Size(bases); /* This better be right */ 1710 if (n < 0) 1711 PyErr_Clear(); 1712 else { 1713 for (i = 0; i < n; i++) { 1714 int status; 1715 PyObject *base = PySequence_GetItem(bases, i); 1716 if (base == NULL) { 1717 Py_DECREF(bases); 1718 return -1; 1719 } 1720 status = merge_class_dict(dict, base); 1721 Py_DECREF(base); 1722 if (status < 0) { 1723 Py_DECREF(bases); 1724 return -1; 1725 } 1726 } 1727 } 1728 Py_DECREF(bases); 1729 } 1730 return 0; 1731 } 1732 1733 /* Helper for PyObject_Dir. 1734 If obj has an attr named attrname that's a list, merge its string 1735 elements into keys of dict. 1736 Return 0 on success, -1 on error. Errors due to not finding the attr, 1737 or the attr not being a list, are suppressed. 1738 */ 1739 1740 static int 1741 merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname) 1742 { 1743 PyObject *list; 1744 int result = 0; 1745 1746 assert(PyDict_Check(dict)); 1747 assert(obj); 1748 assert(attrname); 1749 1750 list = PyObject_GetAttrString(obj, attrname); 1751 if (list == NULL) 1752 PyErr_Clear(); 1753 1754 else if (PyList_Check(list)) { 1755 int i; 1756 for (i = 0; i < PyList_GET_SIZE(list); ++i) { 1757 PyObject *item = PyList_GET_ITEM(list, i); 1758 if (PyString_Check(item)) { 1759 result = PyDict_SetItem(dict, item, Py_None); 1760 if (result < 0) 1761 break; 1762 } 1763 } 1764 if (Py_Py3kWarningFlag && 1765 (strcmp(attrname, "__members__") == 0 || 1766 strcmp(attrname, "__methods__") == 0)) { 1767 if (PyErr_WarnEx(PyExc_DeprecationWarning, 1768 "__members__ and __methods__ not " 1769 "supported in 3.x", 1) < 0) { 1770 Py_XDECREF(list); 1771 return -1; 1772 } 1773 } 1774 } 1775 1776 Py_XDECREF(list); 1777 return result; 1778 } 1779 1780 /* Helper for PyObject_Dir without arguments: returns the local scope. */ 1781 static PyObject * 1782 _dir_locals(void) 1783 { 1784 PyObject *names; 1785 PyObject *locals = PyEval_GetLocals(); 1786 1787 if (locals == NULL) { 1788 PyErr_SetString(PyExc_SystemError, "frame does not exist"); 1789 return NULL; 1790 } 1791 1792 names = PyMapping_Keys(locals); 1793 if (!names) 1794 return NULL; 1795 if (!PyList_Check(names)) { 1796 PyErr_Format(PyExc_TypeError, 1797 "dir(): expected keys() of locals to be a list, " 1798 "not '%.200s'", Py_TYPE(names)->tp_name); 1799 Py_DECREF(names); 1800 return NULL; 1801 } 1802 /* the locals don't need to be DECREF'd */ 1803 return names; 1804 } 1805 1806 /* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__. 1807 We deliberately don't suck up its __class__, as methods belonging to the 1808 metaclass would probably be more confusing than helpful. 1809 */ 1810 static PyObject * 1811 _specialized_dir_type(PyObject *obj) 1812 { 1813 PyObject *result = NULL; 1814 PyObject *dict = PyDict_New(); 1815 1816 if (dict != NULL && merge_class_dict(dict, obj) == 0) 1817 result = PyDict_Keys(dict); 1818 1819 Py_XDECREF(dict); 1820 return result; 1821 } 1822 1823 /* Helper for PyObject_Dir of module objects: returns the module's __dict__. */ 1824 static PyObject * 1825 _specialized_dir_module(PyObject *obj) 1826 { 1827 PyObject *result = NULL; 1828 PyObject *dict = PyObject_GetAttrString(obj, "__dict__"); 1829 1830 if (dict != NULL) { 1831 if (PyDict_Check(dict)) 1832 result = PyDict_Keys(dict); 1833 else { 1834 char *name = PyModule_GetName(obj); 1835 if (name) 1836 PyErr_Format(PyExc_TypeError, 1837 "%.200s.__dict__ is not a dictionary", 1838 name); 1839 } 1840 } 1841 1842 Py_XDECREF(dict); 1843 return result; 1844 } 1845 1846 /* Helper for PyObject_Dir of generic objects: returns __dict__, __class__, 1847 and recursively up the __class__.__bases__ chain. 1848 */ 1849 static PyObject * 1850 _generic_dir(PyObject *obj) 1851 { 1852 PyObject *result = NULL; 1853 PyObject *dict = NULL; 1854 PyObject *itsclass = NULL; 1855 1856 /* Get __dict__ (which may or may not be a real dict...) */ 1857 dict = PyObject_GetAttrString(obj, "__dict__"); 1858 if (dict == NULL) { 1859 PyErr_Clear(); 1860 dict = PyDict_New(); 1861 } 1862 else if (!PyDict_Check(dict)) { 1863 Py_DECREF(dict); 1864 dict = PyDict_New(); 1865 } 1866 else { 1867 /* Copy __dict__ to avoid mutating it. */ 1868 PyObject *temp = PyDict_Copy(dict); 1869 Py_DECREF(dict); 1870 dict = temp; 1871 } 1872 1873 if (dict == NULL) 1874 goto error; 1875 1876 /* Merge in __members__ and __methods__ (if any). 1877 * This is removed in Python 3000. */ 1878 if (merge_list_attr(dict, obj, "__members__") < 0) 1879 goto error; 1880 if (merge_list_attr(dict, obj, "__methods__") < 0) 1881 goto error; 1882 1883 /* Merge in attrs reachable from its class. */ 1884 itsclass = PyObject_GetAttrString(obj, "__class__"); 1885 if (itsclass == NULL) 1886 /* XXX(tomer): Perhaps fall back to obj->ob_type if no 1887 __class__ exists? */ 1888 PyErr_Clear(); 1889 else { 1890 if (merge_class_dict(dict, itsclass) != 0) 1891 goto error; 1892 } 1893 1894 result = PyDict_Keys(dict); 1895 /* fall through */ 1896 error: 1897 Py_XDECREF(itsclass); 1898 Py_XDECREF(dict); 1899 return result; 1900 } 1901 1902 /* Helper for PyObject_Dir: object introspection. 1903 This calls one of the above specialized versions if no __dir__ method 1904 exists. */ 1905 static PyObject * 1906 _dir_object(PyObject *obj) 1907 { 1908 PyObject *result = NULL; 1909 static PyObject *dir_str = NULL; 1910 PyObject *dirfunc; 1911 1912 assert(obj); 1913 if (PyInstance_Check(obj)) { 1914 dirfunc = PyObject_GetAttrString(obj, "__dir__"); 1915 if (dirfunc == NULL) { 1916 if (PyErr_ExceptionMatches(PyExc_AttributeError)) 1917 PyErr_Clear(); 1918 else 1919 return NULL; 1920 } 1921 } 1922 else { 1923 dirfunc = _PyObject_LookupSpecial(obj, "__dir__", &dir_str); 1924 if (PyErr_Occurred()) 1925 return NULL; 1926 } 1927 if (dirfunc == NULL) { 1928 /* use default implementation */ 1929 if (PyModule_Check(obj)) 1930 result = _specialized_dir_module(obj); 1931 else if (PyType_Check(obj) || PyClass_Check(obj)) 1932 result = _specialized_dir_type(obj); 1933 else 1934 result = _generic_dir(obj); 1935 } 1936 else { 1937 /* use __dir__ */ 1938 result = PyObject_CallFunctionObjArgs(dirfunc, NULL); 1939 Py_DECREF(dirfunc); 1940 if (result == NULL) 1941 return NULL; 1942 1943 /* result must be a list */ 1944 /* XXX(gbrandl): could also check if all items are strings */ 1945 if (!PyList_Check(result)) { 1946 PyErr_Format(PyExc_TypeError, 1947 "__dir__() must return a list, not %.200s", 1948 Py_TYPE(result)->tp_name); 1949 Py_DECREF(result); 1950 result = NULL; 1951 } 1952 } 1953 1954 return result; 1955 } 1956 1957 /* Implementation of dir() -- if obj is NULL, returns the names in the current 1958 (local) scope. Otherwise, performs introspection of the object: returns a 1959 sorted list of attribute names (supposedly) accessible from the object 1960 */ 1961 PyObject * 1962 PyObject_Dir(PyObject *obj) 1963 { 1964 PyObject * result; 1965 1966 if (obj == NULL) 1967 /* no object -- introspect the locals */ 1968 result = _dir_locals(); 1969 else 1970 /* object -- introspect the object */ 1971 result = _dir_object(obj); 1972 1973 assert(result == NULL || PyList_Check(result)); 1974 1975 if (result != NULL && PyList_Sort(result) != 0) { 1976 /* sorting the list failed */ 1977 Py_DECREF(result); 1978 result = NULL; 1979 } 1980 1981 return result; 1982 } 1983 1984 /* 1985 NoObject is usable as a non-NULL undefined value, used by the macro None. 1986 There is (and should be!) no way to create other objects of this type, 1987 so there is exactly one (which is indestructible, by the way). 1988 (XXX This type and the type of NotImplemented below should be unified.) 1989 */ 1990 1991 /* ARGSUSED */ 1992 static PyObject * 1993 none_repr(PyObject *op) 1994 { 1995 return PyString_FromString("None"); 1996 } 1997 1998 /* ARGUSED */ 1999 static void 2000 none_dealloc(PyObject* ignore) 2001 { 2002 /* This should never get called, but we also don't want to SEGV if 2003 * we accidentally decref None out of existence. 2004 */ 2005 Py_FatalError("deallocating None"); 2006 } 2007 2008 2009 static PyTypeObject PyNone_Type = { 2010 PyVarObject_HEAD_INIT(&PyType_Type, 0) 2011 "NoneType", 2012 0, 2013 0, 2014 none_dealloc, /*tp_dealloc*/ /*never called*/ 2015 0, /*tp_print*/ 2016 0, /*tp_getattr*/ 2017 0, /*tp_setattr*/ 2018 0, /*tp_compare*/ 2019 none_repr, /*tp_repr*/ 2020 0, /*tp_as_number*/ 2021 0, /*tp_as_sequence*/ 2022 0, /*tp_as_mapping*/ 2023 (hashfunc)_Py_HashPointer, /*tp_hash */ 2024 }; 2025 2026 PyObject _Py_NoneStruct = { 2027 _PyObject_EXTRA_INIT 2028 1, &PyNone_Type 2029 }; 2030 2031 /* NotImplemented is an object that can be used to signal that an 2032 operation is not implemented for the given type combination. */ 2033 2034 static PyObject * 2035 NotImplemented_repr(PyObject *op) 2036 { 2037 return PyString_FromString("NotImplemented"); 2038 } 2039 2040 static PyTypeObject PyNotImplemented_Type = { 2041 PyVarObject_HEAD_INIT(&PyType_Type, 0) 2042 "NotImplementedType", 2043 0, 2044 0, 2045 none_dealloc, /*tp_dealloc*/ /*never called*/ 2046 0, /*tp_print*/ 2047 0, /*tp_getattr*/ 2048 0, /*tp_setattr*/ 2049 0, /*tp_compare*/ 2050 NotImplemented_repr, /*tp_repr*/ 2051 0, /*tp_as_number*/ 2052 0, /*tp_as_sequence*/ 2053 0, /*tp_as_mapping*/ 2054 0, /*tp_hash */ 2055 }; 2056 2057 PyObject _Py_NotImplementedStruct = { 2058 _PyObject_EXTRA_INIT 2059 1, &PyNotImplemented_Type 2060 }; 2061 2062 void 2063 _Py_ReadyTypes(void) 2064 { 2065 if (PyType_Ready(&PyType_Type) < 0) 2066 Py_FatalError("Can't initialize type type"); 2067 2068 if (PyType_Ready(&_PyWeakref_RefType) < 0) 2069 Py_FatalError("Can't initialize weakref type"); 2070 2071 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0) 2072 Py_FatalError("Can't initialize callable weakref proxy type"); 2073 2074 if (PyType_Ready(&_PyWeakref_ProxyType) < 0) 2075 Py_FatalError("Can't initialize weakref proxy type"); 2076 2077 if (PyType_Ready(&PyBool_Type) < 0) 2078 Py_FatalError("Can't initialize bool type"); 2079 2080 if (PyType_Ready(&PyString_Type) < 0) 2081 Py_FatalError("Can't initialize str type"); 2082 2083 if (PyType_Ready(&PyByteArray_Type) < 0) 2084 Py_FatalError("Can't initialize bytearray type"); 2085 2086 if (PyType_Ready(&PyList_Type) < 0) 2087 Py_FatalError("Can't initialize list type"); 2088 2089 if (PyType_Ready(&PyNone_Type) < 0) 2090 Py_FatalError("Can't initialize None type"); 2091 2092 if (PyType_Ready(&PyNotImplemented_Type) < 0) 2093 Py_FatalError("Can't initialize NotImplemented type"); 2094 2095 if (PyType_Ready(&PyTraceBack_Type) < 0) 2096 Py_FatalError("Can't initialize traceback type"); 2097 2098 if (PyType_Ready(&PySuper_Type) < 0) 2099 Py_FatalError("Can't initialize super type"); 2100 2101 if (PyType_Ready(&PyBaseObject_Type) < 0) 2102 Py_FatalError("Can't initialize object type"); 2103 2104 if (PyType_Ready(&PyRange_Type) < 0) 2105 Py_FatalError("Can't initialize xrange type"); 2106 2107 if (PyType_Ready(&PyDict_Type) < 0) 2108 Py_FatalError("Can't initialize dict type"); 2109 2110 if (PyType_Ready(&PySet_Type) < 0) 2111 Py_FatalError("Can't initialize set type"); 2112 2113 if (PyType_Ready(&PyUnicode_Type) < 0) 2114 Py_FatalError("Can't initialize unicode type"); 2115 2116 if (PyType_Ready(&PySlice_Type) < 0) 2117 Py_FatalError("Can't initialize slice type"); 2118 2119 if (PyType_Ready(&PyStaticMethod_Type) < 0) 2120 Py_FatalError("Can't initialize static method type"); 2121 2122 #ifndef WITHOUT_COMPLEX 2123 if (PyType_Ready(&PyComplex_Type) < 0) 2124 Py_FatalError("Can't initialize complex type"); 2125 #endif 2126 2127 if (PyType_Ready(&PyFloat_Type) < 0) 2128 Py_FatalError("Can't initialize float type"); 2129 2130 if (PyType_Ready(&PyBuffer_Type) < 0) 2131 Py_FatalError("Can't initialize buffer type"); 2132 2133 if (PyType_Ready(&PyLong_Type) < 0) 2134 Py_FatalError("Can't initialize long type"); 2135 2136 if (PyType_Ready(&PyInt_Type) < 0) 2137 Py_FatalError("Can't initialize int type"); 2138 2139 if (PyType_Ready(&PyFrozenSet_Type) < 0) 2140 Py_FatalError("Can't initialize frozenset type"); 2141 2142 if (PyType_Ready(&PyProperty_Type) < 0) 2143 Py_FatalError("Can't initialize property type"); 2144 2145 if (PyType_Ready(&PyMemoryView_Type) < 0) 2146 Py_FatalError("Can't initialize memoryview type"); 2147 2148 if (PyType_Ready(&PyTuple_Type) < 0) 2149 Py_FatalError("Can't initialize tuple type"); 2150 2151 if (PyType_Ready(&PyEnum_Type) < 0) 2152 Py_FatalError("Can't initialize enumerate type"); 2153 2154 if (PyType_Ready(&PyReversed_Type) < 0) 2155 Py_FatalError("Can't initialize reversed type"); 2156 2157 if (PyType_Ready(&PyCode_Type) < 0) 2158 Py_FatalError("Can't initialize code type"); 2159 2160 if (PyType_Ready(&PyFrame_Type) < 0) 2161 Py_FatalError("Can't initialize frame type"); 2162 2163 if (PyType_Ready(&PyCFunction_Type) < 0) 2164 Py_FatalError("Can't initialize builtin function type"); 2165 2166 if (PyType_Ready(&PyMethod_Type) < 0) 2167 Py_FatalError("Can't initialize method type"); 2168 2169 if (PyType_Ready(&PyFunction_Type) < 0) 2170 Py_FatalError("Can't initialize function type"); 2171 2172 if (PyType_Ready(&PyClass_Type) < 0) 2173 Py_FatalError("Can't initialize class type"); 2174 2175 if (PyType_Ready(&PyDictProxy_Type) < 0) 2176 Py_FatalError("Can't initialize dict proxy type"); 2177 2178 if (PyType_Ready(&PyGen_Type) < 0) 2179 Py_FatalError("Can't initialize generator type"); 2180 2181 if (PyType_Ready(&PyGetSetDescr_Type) < 0) 2182 Py_FatalError("Can't initialize get-set descriptor type"); 2183 2184 if (PyType_Ready(&PyWrapperDescr_Type) < 0) 2185 Py_FatalError("Can't initialize wrapper type"); 2186 2187 if (PyType_Ready(&PyInstance_Type) < 0) 2188 Py_FatalError("Can't initialize instance type"); 2189 2190 if (PyType_Ready(&PyEllipsis_Type) < 0) 2191 Py_FatalError("Can't initialize ellipsis type"); 2192 2193 if (PyType_Ready(&PyMemberDescr_Type) < 0) 2194 Py_FatalError("Can't initialize member descriptor type"); 2195 2196 if (PyType_Ready(&PyFile_Type) < 0) 2197 Py_FatalError("Can't initialize file type"); 2198 } 2199 2200 2201 #ifdef Py_TRACE_REFS 2202 2203 void 2204 _Py_NewReference(PyObject *op) 2205 { 2206 _Py_INC_REFTOTAL; 2207 op->ob_refcnt = 1; 2208 _Py_AddToAllObjects(op, 1); 2209 _Py_INC_TPALLOCS(op); 2210 } 2211 2212 void 2213 _Py_ForgetReference(register PyObject *op) 2214 { 2215 #ifdef SLOW_UNREF_CHECK 2216 register PyObject *p; 2217 #endif 2218 if (op->ob_refcnt < 0) 2219 Py_FatalError("UNREF negative refcnt"); 2220 if (op == &refchain || 2221 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) 2222 Py_FatalError("UNREF invalid object"); 2223 #ifdef SLOW_UNREF_CHECK 2224 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { 2225 if (p == op) 2226 break; 2227 } 2228 if (p == &refchain) /* Not found */ 2229 Py_FatalError("UNREF unknown object"); 2230 #endif 2231 op->_ob_next->_ob_prev = op->_ob_prev; 2232 op->_ob_prev->_ob_next = op->_ob_next; 2233 op->_ob_next = op->_ob_prev = NULL; 2234 _Py_INC_TPFREES(op); 2235 } 2236 2237 void 2238 _Py_Dealloc(PyObject *op) 2239 { 2240 destructor dealloc = Py_TYPE(op)->tp_dealloc; 2241 _Py_ForgetReference(op); 2242 (*dealloc)(op); 2243 } 2244 2245 /* Print all live objects. Because PyObject_Print is called, the 2246 * interpreter must be in a healthy state. 2247 */ 2248 void 2249 _Py_PrintReferences(FILE *fp) 2250 { 2251 PyObject *op; 2252 fprintf(fp, "Remaining objects:\n"); 2253 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { 2254 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); 2255 if (PyObject_Print(op, fp, 0) != 0) 2256 PyErr_Clear(); 2257 putc('\n', fp); 2258 } 2259 } 2260 2261 /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this 2262 * doesn't make any calls to the Python C API, so is always safe to call. 2263 */ 2264 void 2265 _Py_PrintReferenceAddresses(FILE *fp) 2266 { 2267 PyObject *op; 2268 fprintf(fp, "Remaining object addresses:\n"); 2269 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) 2270 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, 2271 op->ob_refcnt, Py_TYPE(op)->tp_name); 2272 } 2273 2274 PyObject * 2275 _Py_GetObjects(PyObject *self, PyObject *args) 2276 { 2277 int i, n; 2278 PyObject *t = NULL; 2279 PyObject *res, *op; 2280 2281 if (!PyArg_ParseTuple(args, "i|O", &n, &t)) 2282 return NULL; 2283 op = refchain._ob_next; 2284 res = PyList_New(0); 2285 if (res == NULL) 2286 return NULL; 2287 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { 2288 while (op == self || op == args || op == res || op == t || 2289 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) { 2290 op = op->_ob_next; 2291 if (op == &refchain)
Access to field '_ob_next' results in a dereference of a null pointer (loaded from variable 'op')
(emitted by clang-analyzer)

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

2292 return res; 2293 } 2294 if (PyList_Append(res, op) < 0) { 2295 Py_DECREF(res); 2296 return NULL; 2297 } 2298 op = op->_ob_next; 2299 } 2300 return res; 2301 } 2302 2303 #endif 2304 2305 2306 /* Hack to force loading of capsule.o */ 2307 PyTypeObject *_Py_capsule_hack = &PyCapsule_Type; 2308 2309 2310 /* Hack to force loading of cobject.o */ 2311 PyTypeObject *_Py_cobject_hack = &PyCObject_Type; 2312 2313 2314 /* Hack to force loading of abstract.o */ 2315 Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size; 2316 2317 2318 /* Python's malloc wrappers (see pymem.h) */ 2319 2320 void * 2321 PyMem_Malloc(size_t nbytes) 2322 { 2323 return PyMem_MALLOC(nbytes); 2324 } 2325 2326 void * 2327 PyMem_Realloc(void *p, size_t nbytes) 2328 { 2329 return PyMem_REALLOC(p, nbytes); 2330 } 2331 2332 void 2333 PyMem_Free(void *p) 2334 { 2335 PyMem_FREE(p); 2336 } 2337 2338 void 2339 _PyObject_DebugTypeStats(FILE *out) 2340 { 2341 _PyString_DebugMallocStats(out); 2342 _PyCFunction_DebugMallocStats(out); 2343 _PyDict_DebugMallocStats(out); 2344 _PyFloat_DebugMallocStats(out); 2345 _PyFrame_DebugMallocStats(out); 2346 _PyInt_DebugMallocStats(out); 2347 _PyList_DebugMallocStats(out); 2348 _PyMethod_DebugMallocStats(out); 2349 _PySet_DebugMallocStats(out); 2350 _PyTuple_DebugMallocStats(out);
implicit declaration of function '_PySet_DebugMallocStats'
(emitted by gcc)
implicit declaration of function '_PySet_DebugMallocStats'
(emitted by gcc)
2351 #if Py_USING_UNICODE
implicit declaration of function '_PyTuple_DebugMallocStats'
(emitted by gcc)
implicit declaration of function '_PyTuple_DebugMallocStats'
(emitted by gcc)
2352 _PyUnicode_DebugMallocStats(out); 2353 #endif 2354 } 2355 2356 /* These methods are used to control infinite recursion in repr, str, print, 2357 etc. Container objects that may recursively contain themselves, 2358 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and 2359 Py_ReprLeave() to avoid infinite recursion. 2360 2361 Py_ReprEnter() returns 0 the first time it is called for a particular 2362 object and 1 every time thereafter. It returns -1 if an exception 2363 occurred. Py_ReprLeave() has no return value. 2364 2365 See dictobject.c and listobject.c for examples of use. 2366 */ 2367 2368 #define KEY "Py_Repr" 2369 2370 int 2371 Py_ReprEnter(PyObject *obj) 2372 { 2373 PyObject *dict; 2374 PyObject *list; 2375 Py_ssize_t i; 2376 2377 dict = PyThreadState_GetDict(); 2378 if (dict == NULL) 2379 return 0; 2380 list = PyDict_GetItemString(dict, KEY); 2381 if (list == NULL) { 2382 list = PyList_New(0); 2383 if (list == NULL) 2384 return -1; 2385 if (PyDict_SetItemString(dict, KEY, list) < 0) 2386 return -1; 2387 Py_DECREF(list); 2388 } 2389 i = PyList_GET_SIZE(list); 2390 while (--i >= 0) { 2391 if (PyList_GET_ITEM(list, i) == obj) 2392 return 1; 2393 } 2394 PyList_Append(list, obj); 2395 return 0; 2396 } 2397 2398 void 2399 Py_ReprLeave(PyObject *obj) 2400 { 2401 PyObject *dict; 2402 PyObject *list; 2403 Py_ssize_t i; 2404 2405 dict = PyThreadState_GetDict(); 2406 if (dict == NULL) 2407 return; 2408 list = PyDict_GetItemString(dict, KEY); 2409 if (list == NULL || !PyList_Check(list)) 2410 return; 2411 i = PyList_GET_SIZE(list); 2412 /* Count backwards because we always expect obj to be list[-1] */ 2413 while (--i >= 0) { 2414 if (PyList_GET_ITEM(list, i) == obj) { 2415 PyList_SetSlice(list, i, i + 1, NULL); 2416 break; 2417 } 2418 } 2419 } 2420 2421 /* Trashcan support. */ 2422 2423 /* Current call-stack depth of tp_dealloc calls. */ 2424 int _PyTrash_delete_nesting = 0; 2425 2426 /* List of objects that still need to be cleaned up, singly linked via their 2427 * gc headers' gc_prev pointers. 2428 */ 2429 PyObject *_PyTrash_delete_later = NULL; 2430 2431 /* Add op to the _PyTrash_delete_later list. Called when the current 2432 * call-stack depth gets large. op must be a currently untracked gc'ed 2433 * object, with refcount 0. Py_DECREF must already have been called on it. 2434 */ 2435 void 2436 _PyTrash_deposit_object(PyObject *op) 2437 { 2438 assert(PyObject_IS_GC(op)); 2439 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED); 2440 assert(op->ob_refcnt == 0); 2441 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later; 2442 _PyTrash_delete_later = op; 2443 } 2444 2445 /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when 2446 * the call-stack unwinds again. 2447 */ 2448 void 2449 _PyTrash_destroy_chain(void) 2450 { 2451 while (_PyTrash_delete_later) { 2452 PyObject *op = _PyTrash_delete_later; 2453 destructor dealloc = Py_TYPE(op)->tp_dealloc; 2454 2455 _PyTrash_delete_later = 2456 (PyObject*) _Py_AS_GC(op)->gc.gc_prev; 2457 2458 /* Call the deallocator directly. This used to try to 2459 * fool Py_DECREF into calling it indirectly, but 2460 * Py_DECREF was already called on this object, and in 2461 * assorted non-release builds calling Py_DECREF again ends 2462 * up distorting allocation statistics. 2463 */ 2464 assert(op->ob_refcnt == 0); 2465 ++_PyTrash_delete_nesting; 2466 (*dealloc)(op); 2467 --_PyTrash_delete_nesting; 2468 } 2469 } 2470 2471 #ifdef __cplusplus 2472 } 2473 #endif