weakrefobject.c 23.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include "Python.h"
#include "structmember.h"


#define GET_WEAKREFS_LISTPTR(o) \
        ((PyWeakReference **) PyObject_GET_WEAKREFS_LISTPTR(o))


long
_PyWeakref_GetWeakrefCount(PyWeakReference *head)
{
    long count = 0;

    while (head != NULL) {
        ++count;
        head = head->wr_next;
    }
    return count;
}


static PyWeakReference *
23
new_weakref(PyObject *ob, PyObject *callback)
24 25 26
{
    PyWeakReference *result;

27 28
    result = PyObject_GC_New(PyWeakReference, &_PyWeakref_RefType);
    if (result) {
29
        result->hash = -1;
30 31 32 33 34
        result->wr_object = ob;
        Py_XINCREF(callback);
        result->wr_callback = callback;
        PyObject_GC_Track(result);
    }
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    return result;
}


/* This function clears the passed-in reference and removes it from the
 * list of weak references for the referent.  This is the only code that
 * removes an item from the doubly-linked list of weak references for an
 * object; it is also responsible for clearing the callback slot.
 */
static void
clear_weakref(PyWeakReference *self)
{
    PyObject *callback = self->wr_callback;

    if (PyWeakref_GET_OBJECT(self) != Py_None) {
        PyWeakReference **list = GET_WEAKREFS_LISTPTR(
            PyWeakref_GET_OBJECT(self));

        if (*list == self)
            *list = self->wr_next;
        self->wr_object = Py_None;
        if (self->wr_prev != NULL)
            self->wr_prev->wr_next = self->wr_next;
        if (self->wr_next != NULL)
            self->wr_next->wr_prev = self->wr_prev;
        self->wr_prev = NULL;
        self->wr_next = NULL;
62 63 64 65
    }
    if (callback != NULL) {
        Py_DECREF(callback);
        self->wr_callback = NULL;
66 67 68
    }
}

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
/* Cyclic gc uses this to *just* clear the passed-in reference, leaving
 * the callback intact and uncalled.  It must be possible to call self's
 * tp_dealloc() after calling this, so self has to be left in a sane enough
 * state for that to work.  We expect tp_dealloc to decref the callback
 * then.  The reason for not letting clear_weakref() decref the callback
 * right now is that if the callback goes away, that may in turn trigger
 * another callback (if a weak reference to the callback exists) -- running
 * arbitrary Python code in the middle of gc is a disaster.  The convolution
 * here allows gc to delay triggering such callbacks until the world is in
 * a sane state again.
 */
void
_PyWeakref_ClearRef(PyWeakReference *self)
{
    PyObject *callback;

    assert(self != NULL);
    assert(PyWeakref_Check(self));
    /* Preserve and restore the callback around clear_weakref. */
    callback = self->wr_callback;
    self->wr_callback = NULL;
    clear_weakref(self);
    self->wr_callback = callback;
}
93 94 95 96 97 98

static void
weakref_dealloc(PyWeakReference *self)
{
    PyObject_GC_UnTrack((PyObject *)self);
    clear_weakref(self);
99
    PyObject_GC_Del(self);
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
}


static int
gc_traverse(PyWeakReference *self, visitproc visit, void *arg)
{
    if (self->wr_callback != NULL)
        return visit(self->wr_callback, arg);
    return 0;
}


static int
gc_clear(PyWeakReference *self)
{
    clear_weakref(self);
    return 0;
}


static PyObject *
weakref_call(PyWeakReference *self, PyObject *args, PyObject *kw)
{
    static char *argnames[] = {NULL};

    if (PyArg_ParseTupleAndKeywords(args, kw, ":__call__", argnames)) {
        PyObject *object = PyWeakref_GET_OBJECT(self);
        Py_INCREF(object);
        return (object);
    }
    return NULL;
}


static long
weakref_hash(PyWeakReference *self)
{
    if (self->hash != -1)
        return self->hash;
    if (PyWeakref_GET_OBJECT(self) == Py_None) {
        PyErr_SetString(PyExc_TypeError, "weak object has gone away");
        return -1;
    }
    self->hash = PyObject_Hash(PyWeakref_GET_OBJECT(self));
    return self->hash;
}
146

147 148 149 150 151 152

static PyObject *
weakref_repr(PyWeakReference *self)
{
    char buffer[256];
    if (PyWeakref_GET_OBJECT(self) == Py_None) {
153
        PyOS_snprintf(buffer, sizeof(buffer), "<weakref at %p; dead>", self);
154 155
    }
    else {
156 157 158 159 160 161 162
	char *name = NULL;
	PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self),
						   "__name__");
	if (nameobj == NULL)
		PyErr_Clear();
	else if (PyString_Check(nameobj))
		name = PyString_AS_STRING(nameobj);
163
        PyOS_snprintf(buffer, sizeof(buffer),
164 165 166
		      name ? "<weakref at %p; to '%.50s' at %p (%s)>"
		           : "<weakref at %p; to '%.50s' at %p>",
		      self,
167
		      PyWeakref_GET_OBJECT(self)->ob_type->tp_name,
168 169 170
		      PyWeakref_GET_OBJECT(self),
		      name);
	Py_XDECREF(nameobj);
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    }
    return PyString_FromString(buffer);
}

/* Weak references only support equality, not ordering. Two weak references
   are equal if the underlying objects are equal. If the underlying object has
   gone away, they are equal if they are identical. */

static PyObject *
weakref_richcompare(PyWeakReference* self, PyWeakReference* other, int op)
{
    if (op != Py_EQ || self->ob_type != other->ob_type) {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }
    if (PyWeakref_GET_OBJECT(self) == Py_None
        || PyWeakref_GET_OBJECT(other) == Py_None) {
        PyObject *res = self==other ? Py_True : Py_False;
        Py_INCREF(res);
        return res;
    }
    return PyObject_RichCompare(PyWeakref_GET_OBJECT(self),
                                PyWeakref_GET_OBJECT(other), op);
}


PyTypeObject
_PyWeakref_RefType = {
    PyObject_HEAD_INIT(&PyType_Type)
    0,
    "weakref",
    sizeof(PyWeakReference),
    0,
    (destructor)weakref_dealloc,/*tp_dealloc*/
    0,	                        /*tp_print*/
    0,                          /*tp_getattr*/
    0,                          /*tp_setattr*/
    0,	                        /*tp_compare*/
    (reprfunc)weakref_repr,     /*tp_repr*/
    0,                          /*tp_as_number*/
    0,                          /*tp_as_sequence*/
    0,                          /*tp_as_mapping*/
    (hashfunc)weakref_hash,      /*tp_hash*/
    (ternaryfunc)weakref_call,  /*tp_call*/
    0,                          /*tp_str*/
    0,                          /*tp_getattro*/
    0,                          /*tp_setattro*/
    0,                          /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_RICHCOMPARE,
    0,                          /*tp_doc*/
    (traverseproc)gc_traverse,  /*tp_traverse*/
    (inquiry)gc_clear,          /*tp_clear*/
    (richcmpfunc)weakref_richcompare,	/*tp_richcompare*/
    0,				/*tp_weaklistoffset*/
};


static int
proxy_checkref(PyWeakReference *proxy)
{
    if (PyWeakref_GET_OBJECT(proxy) == Py_None) {
        PyErr_SetString(PyExc_ReferenceError,
                        "weakly-referenced object no longer exists");
        return 0;
    }
    return 1;
}


240 241 242 243 244 245 246 247 248 249 250
/* If a parameter is a proxy, check that it is still "live" and wrap it,
 * replacing the original value with the raw object.  Raises ReferenceError
 * if the param is a dead proxy.
 */
#define UNWRAP(o) \
        if (PyWeakref_CheckProxy(o)) { \
            if (!proxy_checkref((PyWeakReference *)o)) \
                return NULL; \
            o = PyWeakref_GET_OBJECT(o); \
        }

251 252 253 254 255 256 257
#define UNWRAP_I(o) \
        if (PyWeakref_CheckProxy(o)) { \
            if (!proxy_checkref((PyWeakReference *)o)) \
                return -1; \
            o = PyWeakref_GET_OBJECT(o); \
        }

258 259
#define WRAP_UNARY(method, generic) \
    static PyObject * \
260 261 262
    method(PyObject *proxy) { \
        UNWRAP(proxy); \
        return generic(proxy); \
263 264 265 266
    }

#define WRAP_BINARY(method, generic) \
    static PyObject * \
267 268 269 270
    method(PyObject *x, PyObject *y) { \
        UNWRAP(x); \
        UNWRAP(y); \
        return generic(x, y); \
271 272
    }

273 274
/* Note that the third arg needs to be checked for NULL since the tp_call
 * slot can receive NULL for this arg.
275
 */
276 277
#define WRAP_TERNARY(method, generic) \
    static PyObject * \
278 279
    method(PyObject *proxy, PyObject *v, PyObject *w) { \
        UNWRAP(proxy); \
280
        UNWRAP(v); \
281 282 283
        if (w != NULL) \
            UNWRAP(w); \
        return generic(proxy, v, w); \
284 285 286 287 288 289 290 291 292 293 294 295 296
    }


/* direct slots */

WRAP_BINARY(proxy_getattr, PyObject_GetAttr)
WRAP_UNARY(proxy_str, PyObject_Str)
WRAP_TERNARY(proxy_call, PyEval_CallObjectWithKeywords)

static PyObject *
proxy_repr(PyWeakReference *proxy)
{
    char buf[160];
297
    PyOS_snprintf(buf, sizeof(buf),
298
		  "<weakproxy at %p to %.100s at %p>", proxy,
299 300
		  PyWeakref_GET_OBJECT(proxy)->ob_type->tp_name,
		  PyWeakref_GET_OBJECT(proxy));
301 302 303 304 305 306 307 308 309 310 311 312 313
    return PyString_FromString(buf);
}


static int
proxy_setattr(PyWeakReference *proxy, PyObject *name, PyObject *value)
{
    if (!proxy_checkref(proxy))
        return -1;
    return PyObject_SetAttr(PyWeakref_GET_OBJECT(proxy), name, value);
}

static int
314
proxy_compare(PyObject *proxy, PyObject *v)
315
{
316 317 318
    UNWRAP_I(proxy);
    UNWRAP_I(v);
    return PyObject_Compare(proxy, v);
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
}

/* number slots */
WRAP_BINARY(proxy_add, PyNumber_Add)
WRAP_BINARY(proxy_sub, PyNumber_Subtract)
WRAP_BINARY(proxy_mul, PyNumber_Multiply)
WRAP_BINARY(proxy_div, PyNumber_Divide)
WRAP_BINARY(proxy_mod, PyNumber_Remainder)
WRAP_BINARY(proxy_divmod, PyNumber_Divmod)
WRAP_TERNARY(proxy_pow, PyNumber_Power)
WRAP_UNARY(proxy_neg, PyNumber_Negative)
WRAP_UNARY(proxy_pos, PyNumber_Positive)
WRAP_UNARY(proxy_abs, PyNumber_Absolute)
WRAP_UNARY(proxy_invert, PyNumber_Invert)
WRAP_BINARY(proxy_lshift, PyNumber_Lshift)
WRAP_BINARY(proxy_rshift, PyNumber_Rshift)
WRAP_BINARY(proxy_and, PyNumber_And)
WRAP_BINARY(proxy_xor, PyNumber_Xor)
WRAP_BINARY(proxy_or, PyNumber_Or)
WRAP_UNARY(proxy_int, PyNumber_Int)
WRAP_UNARY(proxy_long, PyNumber_Long)
WRAP_UNARY(proxy_float, PyNumber_Float)
WRAP_BINARY(proxy_iadd, PyNumber_InPlaceAdd)
WRAP_BINARY(proxy_isub, PyNumber_InPlaceSubtract)
WRAP_BINARY(proxy_imul, PyNumber_InPlaceMultiply)
WRAP_BINARY(proxy_idiv, PyNumber_InPlaceDivide)
WRAP_BINARY(proxy_imod, PyNumber_InPlaceRemainder)
WRAP_TERNARY(proxy_ipow, PyNumber_InPlacePower)
WRAP_BINARY(proxy_ilshift, PyNumber_InPlaceLshift)
WRAP_BINARY(proxy_irshift, PyNumber_InPlaceRshift)
WRAP_BINARY(proxy_iand, PyNumber_InPlaceAnd)
WRAP_BINARY(proxy_ixor, PyNumber_InPlaceXor)
WRAP_BINARY(proxy_ior, PyNumber_InPlaceOr)

353
static int
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
proxy_nonzero(PyWeakReference *proxy)
{
    PyObject *o = PyWeakref_GET_OBJECT(proxy);
    if (!proxy_checkref(proxy))
        return 1;
    if (o->ob_type->tp_as_number &&
        o->ob_type->tp_as_number->nb_nonzero)
        return (*o->ob_type->tp_as_number->nb_nonzero)(o);
    else
        return 1;
}

/* sequence slots */

static PyObject *
proxy_slice(PyWeakReference *proxy, int i, int j)
{
    if (!proxy_checkref(proxy))
        return NULL;
    return PySequence_GetSlice(PyWeakref_GET_OBJECT(proxy), i, j);
}

static int
proxy_ass_slice(PyWeakReference *proxy, int i, int j, PyObject *value)
{
    if (!proxy_checkref(proxy))
        return -1;
    return PySequence_SetSlice(PyWeakref_GET_OBJECT(proxy), i, j, value);
}

static int
proxy_contains(PyWeakReference *proxy, PyObject *value)
{
    if (!proxy_checkref(proxy))
        return -1;
    return PySequence_Contains(PyWeakref_GET_OBJECT(proxy), value);
}


/* mapping slots */

static int
proxy_length(PyWeakReference *proxy)
{
    if (!proxy_checkref(proxy))
        return -1;
    return PyObject_Length(PyWeakref_GET_OBJECT(proxy));
}

WRAP_BINARY(proxy_getitem, PyObject_GetItem)

static int
proxy_setitem(PyWeakReference *proxy, PyObject *key, PyObject *value)
{
    if (!proxy_checkref(proxy))
        return -1;
410 411 412 413 414

    if (value == NULL)
        return PyObject_DelItem(PyWeakref_GET_OBJECT(proxy), key);
    else
        return PyObject_SetItem(PyWeakref_GET_OBJECT(proxy), key, value);
415 416
}

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
/* iterator slots */

static PyObject *
proxy_iter(PyWeakReference *proxy)
{
    if (!proxy_checkref(proxy))
        return NULL;
    return PyObject_GetIter(PyWeakref_GET_OBJECT(proxy));
}

static PyObject *
proxy_iternext(PyWeakReference *proxy)
{
    if (!proxy_checkref(proxy))
        return NULL;
    return PyIter_Next(PyWeakref_GET_OBJECT(proxy));
}

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

static PyNumberMethods proxy_as_number = {
    (binaryfunc)proxy_add,      /*nb_add*/
    (binaryfunc)proxy_sub,      /*nb_subtract*/
    (binaryfunc)proxy_mul,      /*nb_multiply*/
    (binaryfunc)proxy_div,      /*nb_divide*/
    (binaryfunc)proxy_mod,      /*nb_remainder*/
    (binaryfunc)proxy_divmod,   /*nb_divmod*/
    (ternaryfunc)proxy_pow,     /*nb_power*/
    (unaryfunc)proxy_neg,       /*nb_negative*/
    (unaryfunc)proxy_pos,       /*nb_positive*/
    (unaryfunc)proxy_abs,       /*nb_absolute*/
    (inquiry)proxy_nonzero,     /*nb_nonzero*/
    (unaryfunc)proxy_invert,    /*nb_invert*/
    (binaryfunc)proxy_lshift,   /*nb_lshift*/
    (binaryfunc)proxy_rshift,   /*nb_rshift*/
    (binaryfunc)proxy_and,      /*nb_and*/
    (binaryfunc)proxy_xor,      /*nb_xor*/
    (binaryfunc)proxy_or,       /*nb_or*/
    (coercion)0,                /*nb_coerce*/
    (unaryfunc)proxy_int,       /*nb_int*/
    (unaryfunc)proxy_long,      /*nb_long*/
    (unaryfunc)proxy_float,     /*nb_float*/
    (unaryfunc)0,               /*nb_oct*/
    (unaryfunc)0,               /*nb_hex*/
    (binaryfunc)proxy_iadd,     /*nb_inplace_add*/
    (binaryfunc)proxy_isub,     /*nb_inplace_subtract*/
    (binaryfunc)proxy_imul,     /*nb_inplace_multiply*/
    (binaryfunc)proxy_idiv,     /*nb_inplace_divide*/
    (binaryfunc)proxy_imod,     /*nb_inplace_remainder*/
    (ternaryfunc)proxy_ipow,    /*nb_inplace_power*/
    (binaryfunc)proxy_ilshift,  /*nb_inplace_lshift*/
    (binaryfunc)proxy_irshift,  /*nb_inplace_rshift*/
    (binaryfunc)proxy_iand,     /*nb_inplace_and*/
    (binaryfunc)proxy_ixor,     /*nb_inplace_xor*/
    (binaryfunc)proxy_ior,      /*nb_inplace_or*/
};

static PySequenceMethods proxy_as_sequence = {
    (inquiry)proxy_length,      /*sq_length*/
    0,                          /*sq_concat*/
    0,                          /*sq_repeat*/
    0,                          /*sq_item*/
    (intintargfunc)proxy_slice, /*sq_slice*/
    0,                          /*sq_ass_item*/
    (intintobjargproc)proxy_ass_slice, /*sq_ass_slice*/
    (objobjproc)proxy_contains, /* sq_contains */
};

static PyMappingMethods proxy_as_mapping = {
    (inquiry)proxy_length,      /*mp_length*/
    (binaryfunc)proxy_getitem,  /*mp_subscript*/
    (objobjargproc)proxy_setitem, /*mp_ass_subscript*/
};


PyTypeObject
_PyWeakref_ProxyType = {
    PyObject_HEAD_INIT(&PyType_Type)
    0,
    "weakproxy",
    sizeof(PyWeakReference),
    0,
    /* methods */
499
    (destructor)weakref_dealloc,        /* tp_dealloc */
500
    0,				        /* tp_print */
501 502 503 504 505 506 507 508 509 510 511 512 513
    0,				        /* tp_getattr */
    0, 				        /* tp_setattr */
    proxy_compare,		        /* tp_compare */
    (unaryfunc)proxy_repr,	        /* tp_repr */
    &proxy_as_number,		        /* tp_as_number */
    &proxy_as_sequence,		        /* tp_as_sequence */
    &proxy_as_mapping,		        /* tp_as_mapping */
    0,	                                /* tp_hash */
    (ternaryfunc)0,	                /* tp_call */
    (unaryfunc)proxy_str,	        /* tp_str */
    (getattrofunc)proxy_getattr,        /* tp_getattro */
    (setattrofunc)proxy_setattr,        /* tp_setattro */
    0,				        /* tp_as_buffer */
514
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
515 516 517 518 519 520 521 522
    | Py_TPFLAGS_CHECKTYPES,            /* tp_flags */
    0,                                  /* tp_doc */
    (traverseproc)gc_traverse,          /* tp_traverse */
    (inquiry)gc_clear,                  /* tp_clear */
    0,                                  /* tp_richcompare */
    0,                                  /* tp_weaklistoffset */
    (getiterfunc)proxy_iter,            /* tp_iter */
    (iternextfunc)proxy_iternext,       /* tp_iternext */
523 524 525 526 527 528 529 530 531 532 533
};


PyTypeObject
_PyWeakref_CallableProxyType = {
    PyObject_HEAD_INIT(&PyType_Type)
    0,
    "weakcallableproxy",
    sizeof(PyWeakReference),
    0,
    /* methods */
534
    (destructor)weakref_dealloc,        /* tp_dealloc */
535
    0,				        /* tp_print */
536 537 538 539 540 541 542 543 544 545 546 547 548
    0,				        /* tp_getattr */
    0, 				        /* tp_setattr */
    proxy_compare,		        /* tp_compare */
    (unaryfunc)proxy_repr,	        /* tp_repr */
    &proxy_as_number,		        /* tp_as_number */
    &proxy_as_sequence,		        /* tp_as_sequence */
    &proxy_as_mapping,		        /* tp_as_mapping */
    0,	                                /* tp_hash */
    (ternaryfunc)proxy_call,	        /* tp_call */
    (unaryfunc)proxy_str,	        /* tp_str */
    (getattrofunc)proxy_getattr,        /* tp_getattro */
    (setattrofunc)proxy_setattr,        /* tp_setattro */
    0,				        /* tp_as_buffer */
549
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
550 551 552 553 554 555 556 557
    | Py_TPFLAGS_CHECKTYPES,            /* tp_flags */
    0,                                  /* tp_doc */
    (traverseproc)gc_traverse,          /* tp_traverse */
    (inquiry)gc_clear,                  /* tp_clear */
    0,                                  /* tp_richcompare */
    0,                                  /* tp_weaklistoffset */
    (getiterfunc)proxy_iter,            /* tp_iter */
    (iternextfunc)proxy_iternext,       /* tp_iternext */
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
};


/* Given the head of an object's list of weak references, extract the
 * two callback-less refs (ref and proxy).  Used to determine if the
 * shared references exist and to determine the back link for newly
 * inserted references.
 */
static void
get_basic_refs(PyWeakReference *head,
               PyWeakReference **refp, PyWeakReference **proxyp)
{
    *refp = NULL;
    *proxyp = NULL;

    if (head != NULL && head->wr_callback == NULL) {
        if (head->ob_type == &_PyWeakref_RefType) {
            *refp = head;
            head = head->wr_next;
        }
        if (head != NULL && head->wr_callback == NULL) {
            *proxyp = head;
            head = head->wr_next;
        }
    }
}

/* Insert 'newref' in the list after 'prev'.  Both must be non-NULL. */
static void
insert_after(PyWeakReference *newref, PyWeakReference *prev)
{
    newref->wr_prev = prev;
    newref->wr_next = prev->wr_next;
    if (prev->wr_next != NULL)
        prev->wr_next->wr_prev = newref;
    prev->wr_next = newref;
}

/* Insert 'newref' at the head of the list; 'list' points to the variable
 * that stores the head.
 */
static void
insert_head(PyWeakReference *newref, PyWeakReference **list)
{
    PyWeakReference *next = *list;

    newref->wr_prev = NULL;
    newref->wr_next = next;
    if (next != NULL)
        next->wr_prev = newref;
    *list = newref;
}


PyObject *
PyWeakref_NewRef(PyObject *ob, PyObject *callback)
{
    PyWeakReference *result = NULL;
    PyWeakReference **list;
    PyWeakReference *ref, *proxy;

    if (!PyType_SUPPORTS_WEAKREFS(ob->ob_type)) {
        PyErr_Format(PyExc_TypeError,
621
		     "cannot create weak reference to '%s' object",
622 623 624 625 626
                     ob->ob_type->tp_name);
        return NULL;
    }
    list = GET_WEAKREFS_LISTPTR(ob);
    get_basic_refs(*list, &ref, &proxy);
627 628 629
    if (callback == Py_None)
        callback = NULL;
    if (callback == NULL)
630 631 632
        /* return existing weak reference if it exists */
        result = ref;
    if (result != NULL)
633
        Py_INCREF(result);
634
    else {
635 636 637 638 639
        /* Note: new_weakref() can trigger cyclic GC, so the weakref
           list on ob can be mutated.  This means that the ref and
           proxy pointers we got back earlier may have been collected,
           so we need to compute these values again before we use
           them. */
640
        result = new_weakref(ob, callback);
641 642 643 644 645
        if (result != NULL) {
            if (callback == NULL) {
                insert_head(result, list);
            }
            else {
646
                PyWeakReference *prev;
647

648 649
                get_basic_refs(*list, &ref, &proxy);
                prev = (proxy == NULL) ? ref : proxy;
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
                if (prev == NULL)
                    insert_head(result, list);
                else
                    insert_after(result, prev);
            }
        }
    }
    return (PyObject *) result;
}


PyObject *
PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
{
    PyWeakReference *result = NULL;
    PyWeakReference **list;
    PyWeakReference *ref, *proxy;

    if (!PyType_SUPPORTS_WEAKREFS(ob->ob_type)) {
        PyErr_Format(PyExc_TypeError,
670
		     "cannot create weak reference to '%s' object",
671 672 673 674 675
                     ob->ob_type->tp_name);
        return NULL;
    }
    list = GET_WEAKREFS_LISTPTR(ob);
    get_basic_refs(*list, &ref, &proxy);
676 677
    if (callback == Py_None)
        callback = NULL;
678 679 680 681
    if (callback == NULL)
        /* attempt to return an existing weak reference if it exists */
        result = proxy;
    if (result != NULL)
682
        Py_INCREF(result);
683
    else {
684 685 686 687 688
        /* Note: new_weakref() can trigger cyclic GC, so the weakref
           list on ob can be mutated.  This means that the ref and
           proxy pointers we got back earlier may have been collected,
           so we need to compute these values again before we use
           them. */
689
        result = new_weakref(ob, callback);
690 691 692 693 694 695 696
        if (result != NULL) {
            PyWeakReference *prev;

            if (PyCallable_Check(ob))
                result->ob_type = &_PyWeakref_CallableProxyType;
            else
                result->ob_type = &_PyWeakref_ProxyType;
697
            get_basic_refs(*list, &ref, &proxy);
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
            if (callback == NULL)
                prev = ref;
            else
                prev = (proxy == NULL) ? ref : proxy;

            if (prev == NULL)
                insert_head(result, list);
            else
                insert_after(result, prev);
        }
    }
    return (PyObject *) result;
}


PyObject *
PyWeakref_GetObject(PyObject *ref)
{
    if (ref == NULL || !PyWeakref_Check(ref)) {
        PyErr_BadInternalCall();
        return NULL;
    }
    return PyWeakref_GET_OBJECT(ref);
}


724 725 726 727 728 729 730 731 732 733 734 735
static void
handle_callback(PyWeakReference *ref, PyObject *callback)
{
    PyObject *cbresult = PyObject_CallFunction(callback, "O", ref);

    if (cbresult == NULL)
        PyErr_WriteUnraisable(callback);
    else
        Py_DECREF(cbresult);
}

/* This function is called by the tp_dealloc handler to clear weak references.
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
 *
 * This iterates through the weak references for 'object' and calls callbacks
 * for those references which have one.  It returns when all callbacks have
 * been attempted.
 */
void
PyObject_ClearWeakRefs(PyObject *object)
{
    PyWeakReference **list;

    if (object == NULL
        || !PyType_SUPPORTS_WEAKREFS(object->ob_type)
        || object->ob_refcnt != 0) {
        PyErr_BadInternalCall();
        return;
    }
    list = GET_WEAKREFS_LISTPTR(object);
    /* Remove the callback-less basic and proxy references */
    if (*list != NULL && (*list)->wr_callback == NULL) {
        clear_weakref(*list);
        if (*list != NULL && (*list)->wr_callback == NULL)
            clear_weakref(*list);
    }
    if (*list != NULL) {
760 761 762 763
        PyWeakReference *current = *list;
        int count = _PyWeakref_GetWeakrefCount(current);
        int restore_error = PyErr_Occurred() ? 1 : 0;
        PyObject *err_type, *err_value, *err_tb;
764

765 766
        if (restore_error)
            PyErr_Fetch(&err_type, &err_value, &err_tb);
767 768 769
        if (count == 1) {
            PyObject *callback = current->wr_callback;

770
            current->wr_callback = NULL;
771
            clear_weakref(current);
772
            handle_callback(current, callback);
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
            Py_DECREF(callback);
        }
        else {
            PyObject *tuple = PyTuple_New(count * 2);
            int i = 0;

            for (i = 0; i < count; ++i) {
                PyWeakReference *next = current->wr_next;

                Py_INCREF(current);
                PyTuple_SET_ITEM(tuple, i * 2, (PyObject *) current);
                PyTuple_SET_ITEM(tuple, i * 2 + 1, current->wr_callback);
                current->wr_callback = NULL;
                clear_weakref(current);
                current = next;
            }
            for (i = 0; i < count; ++i) {
                PyObject *current = PyTuple_GET_ITEM(tuple, i * 2);
                PyObject *callback = PyTuple_GET_ITEM(tuple, i * 2 + 1);
792 793

                handle_callback((PyWeakReference *)current, callback);
794 795 796
            }
            Py_DECREF(tuple);
        }
797 798
        if (restore_error)
            PyErr_Restore(err_type, err_value, err_tb);
799 800
    }
}