_xxsubinterpretersmodule.c 73.6 KB
Newer Older
1 2 3 4 5 6

/* interpreters module */
/* low-level access to interpreter primitives */

#include "Python.h"
#include "frameobject.h"
7
#include "pycore_pystate.h"
8 9


10 11 12 13 14 15 16 17
static char *
_copy_raw_string(PyObject *strobj)
{
    const char *str = PyUnicode_AsUTF8(strobj);
    if (str == NULL) {
        return NULL;
    }
    char *copied = PyMem_Malloc(strlen(str)+1);
18
    if (copied == NULL) {
19 20 21 22 23 24 25
        PyErr_NoMemory();
        return NULL;
    }
    strcpy(copied, str);
    return copied;
}

26 27 28
static PyInterpreterState *
_get_current(void)
{
29
    // _PyInterpreterState_Get() aborts if lookup fails, so don't need
30
    // to check the result for NULL.
31
    return _PyInterpreterState_Get();
32 33 34
}

static int64_t
35
_coerce_id(PyObject *orig)
36
{
37 38
    PyObject *pyid = PyNumber_Long(orig);
    if (pyid == NULL) {
39
        if (PyErr_ExceptionMatches(PyExc_TypeError)) {
40 41
            PyErr_Format(PyExc_TypeError,
                         "'id' must be a non-negative int, got %R", orig);
42 43
        }
        else {
44 45
            PyErr_Format(PyExc_ValueError,
                         "'id' must be a non-negative int, got %R", orig);
46 47 48
        }
        return -1;
    }
49 50 51
    int64_t id = PyLong_AsLongLong(pyid);
    Py_DECREF(pyid);
    if (id == -1 && PyErr_Occurred() != NULL) {
52
        if (!PyErr_ExceptionMatches(PyExc_OverflowError)) {
53 54
            PyErr_Format(PyExc_ValueError,
                         "'id' must be a non-negative int, got %R", orig);
55
        }
56 57
        return -1;
    }
58 59 60
    if (id < 0) {
        PyErr_Format(PyExc_ValueError,
                     "'id' must be a non-negative int, got %R", orig);
61 62
        return -1;
    }
63
    return id;
64 65
}

66

67 68
/* data-sharing-specific code ***********************************************/

69 70
struct _sharednsitem {
    char *name;
71
    _PyCrossInterpreterData data;
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 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
};

static int
_sharednsitem_init(struct _sharednsitem *item, PyObject *key, PyObject *value)
{
    item->name = _copy_raw_string(key);
    if (item->name == NULL) {
        return -1;
    }
    if (_PyObject_GetCrossInterpreterData(value, &item->data) != 0) {
        return -1;
    }
    return 0;
}

static void
_sharednsitem_clear(struct _sharednsitem *item)
{
    if (item->name != NULL) {
        PyMem_Free(item->name);
    }
    _PyCrossInterpreterData_Release(&item->data);
}

static int
_sharednsitem_apply(struct _sharednsitem *item, PyObject *ns)
{
    PyObject *name = PyUnicode_FromString(item->name);
    if (name == NULL) {
        return -1;
    }
    PyObject *value = _PyCrossInterpreterData_NewObject(&item->data);
    if (value == NULL) {
        Py_DECREF(name);
        return -1;
    }
    int res = PyDict_SetItem(ns, name, value);
    Py_DECREF(name);
    Py_DECREF(value);
    return res;
}

typedef struct _sharedns {
    Py_ssize_t len;
    struct _sharednsitem* items;
} _sharedns;

static _sharedns *
_sharedns_new(Py_ssize_t len)
{
    _sharedns *shared = PyMem_NEW(_sharedns, 1);
    if (shared == NULL) {
        PyErr_NoMemory();
        return NULL;
    }
    shared->len = len;
    shared->items = PyMem_NEW(struct _sharednsitem, len);
    if (shared->items == NULL) {
        PyErr_NoMemory();
        PyMem_Free(shared);
        return NULL;
    }
    return shared;
}
136

137 138
static void
_sharedns_free(_sharedns *shared)
139
{
140 141
    for (Py_ssize_t i=0; i < shared->len; i++) {
        _sharednsitem_clear(&shared->items[i]);
142
    }
143 144
    PyMem_Free(shared->items);
    PyMem_Free(shared);
145 146
}

147 148
static _sharedns *
_get_shared_ns(PyObject *shareable)
149 150 151 152 153 154 155 156 157
{
    if (shareable == NULL || shareable == Py_None) {
        return NULL;
    }
    Py_ssize_t len = PyDict_Size(shareable);
    if (len == 0) {
        return NULL;
    }

158
    _sharedns *shared = _sharedns_new(len);
159 160 161 162 163 164 165 166 167
    if (shared == NULL) {
        return NULL;
    }
    Py_ssize_t pos = 0;
    for (Py_ssize_t i=0; i < len; i++) {
        PyObject *key, *value;
        if (PyDict_Next(shareable, &pos, &key, &value) == 0) {
            break;
        }
168
        if (_sharednsitem_init(&shared->items[i], key, value) != 0) {
169 170 171 172
            break;
        }
    }
    if (PyErr_Occurred()) {
173
        _sharedns_free(shared);
174 175 176 177 178 179
        return NULL;
    }
    return shared;
}

static int
180
_sharedns_apply(_sharedns *shared, PyObject *ns)
181
{
182 183 184 185
    for (Py_ssize_t i=0; i < shared->len; i++) {
        if (_sharednsitem_apply(&shared->items[i], ns) != 0) {
            return -1;
        }
186
    }
187
    return 0;
188 189 190 191 192 193 194 195
}

// Ultimately we'd like to preserve enough information about the
// exception and traceback that we could re-constitute (or at least
// simulate, a la traceback.TracebackException), and even chain, a copy
// of the exception in the calling interpreter.

typedef struct _sharedexception {
196
    char *name;
197 198 199 200
    char *msg;
} _sharedexception;

static _sharedexception *
201
_sharedexception_new(void)
202 203 204
{
    _sharedexception *err = PyMem_NEW(_sharedexception, 1);
    if (err == NULL) {
205
        PyErr_NoMemory();
206 207
        return NULL;
    }
208 209 210 211 212 213 214 215 216 217
    err->name = NULL;
    err->msg = NULL;
    return err;
}

static void
_sharedexception_clear(_sharedexception *exc)
{
    if (exc->name != NULL) {
        PyMem_Free(exc->name);
218
    }
219 220
    if (exc->msg != NULL) {
        PyMem_Free(exc->msg);
221 222 223
    }
}

224 225 226 227 228 229
static void
_sharedexception_free(_sharedexception *exc)
{
    _sharedexception_clear(exc);
    PyMem_Free(exc);
}
230

231 232
static _sharedexception *
_sharedexception_bind(PyObject *exctype, PyObject *exc, PyObject *tb)
233
{
234 235
    assert(exctype != NULL);
    char *failure = NULL;
236

237 238 239
    _sharedexception *err = _sharedexception_new();
    if (err == NULL) {
        goto finally;
240
    }
241 242 243 244 245 246 247 248 249 250 251 252 253 254

    PyObject *name = PyUnicode_FromFormat("%S", exctype);
    if (name == NULL) {
        failure = "unable to format exception type name";
        goto finally;
    }
    err->name = _copy_raw_string(name);
    Py_DECREF(name);
    if (err->name == NULL) {
        if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
            failure = "out of memory copying exception type name";
        }
        failure = "unable to encode and copy exception type name";
        goto finally;
255 256
    }

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    if (exc != NULL) {
        PyObject *msg = PyUnicode_FromFormat("%S", exc);
        if (msg == NULL) {
            failure = "unable to format exception message";
            goto finally;
        }
        err->msg = _copy_raw_string(msg);
        Py_DECREF(msg);
        if (err->msg == NULL) {
            if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
                failure = "out of memory copying exception message";
            }
            failure = "unable to encode and copy exception message";
            goto finally;
        }
    }

finally:
    if (failure != NULL) {
        PyErr_Clear();
        if (err->name != NULL) {
            PyMem_Free(err->name);
            err->name = NULL;
        }
        err->msg = failure;
    }
    return err;
284 285 286
}

static void
287
_sharedexception_apply(_sharedexception *exc, PyObject *wrapperclass)
288
{
289 290 291 292 293 294 295 296 297 298 299 300 301 302
    if (exc->name != NULL) {
        if (exc->msg != NULL) {
            PyErr_Format(wrapperclass, "%s: %s",  exc->name, exc->msg);
        }
        else {
            PyErr_SetString(wrapperclass, exc->name);
        }
    }
    else if (exc->msg != NULL) {
        PyErr_SetString(wrapperclass, exc->msg);
    }
    else {
        PyErr_SetNone(wrapperclass);
    }
303 304
}

305 306

/* channel-specific code ****************************************************/
307

308 309 310 311
#define CHANNEL_SEND 1
#define CHANNEL_BOTH 0
#define CHANNEL_RECV -1

312 313 314 315
static PyObject *ChannelError;
static PyObject *ChannelNotFoundError;
static PyObject *ChannelClosedError;
static PyObject *ChannelEmptyError;
316
static PyObject *ChannelNotEmptyError;
317 318 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 353 354 355 356 357 358 359 360 361 362

static int
channel_exceptions_init(PyObject *ns)
{
    // XXX Move the exceptions into per-module memory?

    // A channel-related operation failed.
    ChannelError = PyErr_NewException("_xxsubinterpreters.ChannelError",
                                      PyExc_RuntimeError, NULL);
    if (ChannelError == NULL) {
        return -1;
    }
    if (PyDict_SetItemString(ns, "ChannelError", ChannelError) != 0) {
        return -1;
    }

    // An operation tried to use a channel that doesn't exist.
    ChannelNotFoundError = PyErr_NewException(
            "_xxsubinterpreters.ChannelNotFoundError", ChannelError, NULL);
    if (ChannelNotFoundError == NULL) {
        return -1;
    }
    if (PyDict_SetItemString(ns, "ChannelNotFoundError", ChannelNotFoundError) != 0) {
        return -1;
    }

    // An operation tried to use a closed channel.
    ChannelClosedError = PyErr_NewException(
            "_xxsubinterpreters.ChannelClosedError", ChannelError, NULL);
    if (ChannelClosedError == NULL) {
        return -1;
    }
    if (PyDict_SetItemString(ns, "ChannelClosedError", ChannelClosedError) != 0) {
        return -1;
    }

    // An operation tried to pop from an empty channel.
    ChannelEmptyError = PyErr_NewException(
            "_xxsubinterpreters.ChannelEmptyError", ChannelError, NULL);
    if (ChannelEmptyError == NULL) {
        return -1;
    }
    if (PyDict_SetItemString(ns, "ChannelEmptyError", ChannelEmptyError) != 0) {
        return -1;
    }

363 364 365 366 367 368 369 370 371 372
    // An operation tried to close a non-empty channel.
    ChannelNotEmptyError = PyErr_NewException(
            "_xxsubinterpreters.ChannelNotEmptyError", ChannelError, NULL);
    if (ChannelNotEmptyError == NULL) {
        return -1;
    }
    if (PyDict_SetItemString(ns, "ChannelNotEmptyError", ChannelNotEmptyError) != 0) {
        return -1;
    }

373 374 375
    return 0;
}

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 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 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 499 500 501 502 503 504 505 506 507 508
/* the channel queue */

struct _channelitem;

typedef struct _channelitem {
    _PyCrossInterpreterData *data;
    struct _channelitem *next;
} _channelitem;

static _channelitem *
_channelitem_new(void)
{
    _channelitem *item = PyMem_NEW(_channelitem, 1);
    if (item == NULL) {
        PyErr_NoMemory();
        return NULL;
    }
    item->data = NULL;
    item->next = NULL;
    return item;
}

static void
_channelitem_clear(_channelitem *item)
{
    if (item->data != NULL) {
        _PyCrossInterpreterData_Release(item->data);
        PyMem_Free(item->data);
        item->data = NULL;
    }
    item->next = NULL;
}

static void
_channelitem_free(_channelitem *item)
{
    _channelitem_clear(item);
    PyMem_Free(item);
}

static void
_channelitem_free_all(_channelitem *item)
{
    while (item != NULL) {
        _channelitem *last = item;
        item = item->next;
        _channelitem_free(last);
    }
}

static _PyCrossInterpreterData *
_channelitem_popped(_channelitem *item)
{
    _PyCrossInterpreterData *data = item->data;
    item->data = NULL;
    _channelitem_free(item);
    return data;
}

typedef struct _channelqueue {
    int64_t count;
    _channelitem *first;
    _channelitem *last;
} _channelqueue;

static _channelqueue *
_channelqueue_new(void)
{
    _channelqueue *queue = PyMem_NEW(_channelqueue, 1);
    if (queue == NULL) {
        PyErr_NoMemory();
        return NULL;
    }
    queue->count = 0;
    queue->first = NULL;
    queue->last = NULL;
    return queue;
}

static void
_channelqueue_clear(_channelqueue *queue)
{
    _channelitem_free_all(queue->first);
    queue->count = 0;
    queue->first = NULL;
    queue->last = NULL;
}

static void
_channelqueue_free(_channelqueue *queue)
{
    _channelqueue_clear(queue);
    PyMem_Free(queue);
}

static int
_channelqueue_put(_channelqueue *queue, _PyCrossInterpreterData *data)
{
    _channelitem *item = _channelitem_new();
    if (item == NULL) {
        return -1;
    }
    item->data = data;

    queue->count += 1;
    if (queue->first == NULL) {
        queue->first = item;
    }
    else {
        queue->last->next = item;
    }
    queue->last = item;
    return 0;
}

static _PyCrossInterpreterData *
_channelqueue_get(_channelqueue *queue)
{
    _channelitem *item = queue->first;
    if (item == NULL) {
        return NULL;
    }
    queue->first = item->next;
    if (queue->last == item) {
        queue->last = NULL;
    }
    queue->count -= 1;

    return _channelitem_popped(item);
}

/* channel-interpreter associations */

509 510 511 512 513 514 515 516 517 518 519 520 521
struct _channelend;

typedef struct _channelend {
    struct _channelend *next;
    int64_t interp;
    int open;
} _channelend;

static _channelend *
_channelend_new(int64_t interp)
{
    _channelend *end = PyMem_NEW(_channelend, 1);
    if (end == NULL) {
522
        PyErr_NoMemory();
523 524 525 526 527 528 529 530 531
        return NULL;
    }
    end->next = NULL;
    end->interp = interp;
    end->open = 1;
    return end;
}

static void
532 533 534 535 536 537 538 539
_channelend_free(_channelend *end)
{
    PyMem_Free(end);
}

static void
_channelend_free_all(_channelend *end)
{
540 541 542
    while (end != NULL) {
        _channelend *last = end;
        end = end->next;
543
        _channelend_free(last);
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    }
}

static _channelend *
_channelend_find(_channelend *first, int64_t interp, _channelend **pprev)
{
    _channelend *prev = NULL;
    _channelend *end = first;
    while (end != NULL) {
        if (end->interp == interp) {
            break;
        }
        prev = end;
        end = end->next;
    }
    if (pprev != NULL) {
        *pprev = prev;
    }
    return end;
}

565
typedef struct _channelassociations {
566 567 568 569 570 571 572 573
    // Note that the list entries are never removed for interpreter
    // for which the channel is closed.  This should be a problem in
    // practice.  Also, a channel isn't automatically closed when an
    // interpreter is destroyed.
    int64_t numsendopen;
    int64_t numrecvopen;
    _channelend *send;
    _channelend *recv;
574
} _channelends;
575

576 577
static _channelends *
_channelends_new(void)
578
{
579 580
    _channelends *ends = PyMem_NEW(_channelends, 1);
    if (ends== NULL) {
581 582
        return NULL;
    }
583 584 585 586 587 588
    ends->numsendopen = 0;
    ends->numrecvopen = 0;
    ends->send = NULL;
    ends->recv = NULL;
    return ends;
}
589

590 591 592 593 594 595
static void
_channelends_clear(_channelends *ends)
{
    _channelend_free_all(ends->send);
    ends->send = NULL;
    ends->numsendopen = 0;
596

597 598 599 600
    _channelend_free_all(ends->recv);
    ends->recv = NULL;
    ends->numrecvopen = 0;
}
601

602 603 604 605 606
static void
_channelends_free(_channelends *ends)
{
    _channelends_clear(ends);
    PyMem_Free(ends);
607 608 609
}

static _channelend *
610
_channelends_add(_channelends *ends, _channelend *prev, int64_t interp,
611 612 613 614 615 616 617 618 619
                 int send)
{
    _channelend *end = _channelend_new(interp);
    if (end == NULL) {
        return NULL;
    }

    if (prev == NULL) {
        if (send) {
620
            ends->send = end;
621 622
        }
        else {
623
            ends->recv = end;
624 625 626 627 628 629
        }
    }
    else {
        prev->next = end;
    }
    if (send) {
630
        ends->numsendopen += 1;
631 632
    }
    else {
633
        ends->numrecvopen += 1;
634 635 636 637
    }
    return end;
}

638 639
static int
_channelends_associate(_channelends *ends, int64_t interp, int send)
640 641
{
    _channelend *prev;
642
    _channelend *end = _channelend_find(send ? ends->send : ends->recv,
643 644 645 646
                                        interp, &prev);
    if (end != NULL) {
        if (!end->open) {
            PyErr_SetString(ChannelClosedError, "channel already closed");
647
            return -1;
648 649
        }
        // already associated
650 651 652 653
        return 0;
    }
    if (_channelends_add(ends, prev, interp, send) == NULL) {
        return -1;
654
    }
655 656 657 658 659 660 661 662 663 664 665 666 667
    return 0;
}

static int
_channelends_is_open(_channelends *ends)
{
    if (ends->numsendopen != 0 || ends->numrecvopen != 0) {
        return 1;
    }
    if (ends->send == NULL && ends->recv == NULL) {
        return 1;
    }
    return 0;
668 669 670
}

static void
671
_channelends_close_end(_channelends *ends, _channelend *end, int send)
672 673 674
{
    end->open = 0;
    if (send) {
675
        ends->numsendopen -= 1;
676 677
    }
    else {
678
        ends->numrecvopen -= 1;
679 680 681 682
    }
}

static int
683
_channelends_close_interpreter(_channelends *ends, int64_t interp, int which)
684 685 686 687
{
    _channelend *prev;
    _channelend *end;
    if (which >= 0) {  // send/both
688
        end = _channelend_find(ends->send, interp, &prev);
689 690
        if (end == NULL) {
            // never associated so add it
691
            end = _channelends_add(ends, prev, interp, 1);
692
            if (end == NULL) {
693
                return -1;
694 695
            }
        }
696
        _channelends_close_end(ends, end, 1);
697 698
    }
    if (which <= 0) {  // recv/both
699
        end = _channelend_find(ends->recv, interp, &prev);
700 701
        if (end == NULL) {
            // never associated so add it
702
            end = _channelends_add(ends, prev, interp, 0);
703
            if (end == NULL) {
704
                return -1;
705 706
            }
        }
707
        _channelends_close_end(ends, end, 0);
708
    }
709
    return 0;
710 711
}

712
static void
713
_channelends_close_all(_channelends *ends, int which, int force)
714
{
715 716 717
    // XXX Handle the ends.
    // XXX Handle force is True.

718 719 720 721 722
    // Ensure all the "send"-associated interpreters are closed.
    _channelend *end;
    for (end = ends->send; end != NULL; end = end->next) {
        _channelends_close_end(ends, end, 1);
    }
723

724 725 726
    // Ensure all the "recv"-associated interpreters are closed.
    for (end = ends->recv; end != NULL; end = end->next) {
        _channelends_close_end(ends, end, 0);
727
    }
728
}
729

730
/* channels */
731

732
struct _channel;
733 734 735
struct _channel_closing;
static void _channel_clear_closing(struct _channel *);
static void _channel_finish_closing(struct _channel *);
736

737 738 739 740 741
typedef struct _channel {
    PyThread_type_lock mutex;
    _channelqueue *queue;
    _channelends *ends;
    int open;
742
    struct _channel_closing *closing;
743
} _PyChannelState;
744

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
static _PyChannelState *
_channel_new(void)
{
    _PyChannelState *chan = PyMem_NEW(_PyChannelState, 1);
    if (chan == NULL) {
        return NULL;
    }
    chan->mutex = PyThread_allocate_lock();
    if (chan->mutex == NULL) {
        PyMem_Free(chan);
        PyErr_SetString(ChannelError,
                        "can't initialize mutex for new channel");
        return NULL;
    }
    chan->queue = _channelqueue_new();
    if (chan->queue == NULL) {
        PyMem_Free(chan);
        return NULL;
    }
    chan->ends = _channelends_new();
    if (chan->ends == NULL) {
        _channelqueue_free(chan->queue);
        PyMem_Free(chan);
        return NULL;
769
    }
770
    chan->open = 1;
771
    chan->closing = NULL;
772 773
    return chan;
}
774

775 776 777
static void
_channel_free(_PyChannelState *chan)
{
778
    _channel_clear_closing(chan);
779 780 781
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);
    _channelqueue_free(chan->queue);
    _channelends_free(chan->ends);
782
    PyThread_release_lock(chan->mutex);
783 784 785

    PyThread_free_lock(chan->mutex);
    PyMem_Free(chan);
786 787 788 789 790 791 792 793
}

static int
_channel_add(_PyChannelState *chan, int64_t interp,
             _PyCrossInterpreterData *data)
{
    int res = -1;
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);
794 795 796

    if (!chan->open) {
        PyErr_SetString(ChannelClosedError, "channel closed");
797 798
        goto done;
    }
799
    if (_channelends_associate(chan->ends, interp, 1) != 0) {
800 801 802
        goto done;
    }

803 804
    if (_channelqueue_put(chan->queue, data) != 0) {
        goto done;
805 806 807 808 809 810 811 812 813 814 815 816 817 818
    }

    res = 0;
done:
    PyThread_release_lock(chan->mutex);
    return res;
}

static _PyCrossInterpreterData *
_channel_next(_PyChannelState *chan, int64_t interp)
{
    _PyCrossInterpreterData *data = NULL;
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);

819 820
    if (!chan->open) {
        PyErr_SetString(ChannelClosedError, "channel closed");
821 822
        goto done;
    }
823 824
    if (_channelends_associate(chan->ends, interp, 0) != 0) {
        goto done;
825 826
    }

827
    data = _channelqueue_get(chan->queue);
828 829 830 831
    if (data == NULL && !PyErr_Occurred() && chan->closing != NULL) {
        chan->open = 0;
    }

832 833
done:
    PyThread_release_lock(chan->mutex);
834 835 836
    if (chan->queue->count == 0) {
        _channel_finish_closing(chan);
    }
837 838 839
    return data;
}

840
static int
841
_channel_close_interpreter(_PyChannelState *chan, int64_t interp, int end)
842
{
843 844 845 846 847 848
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);

    int res = -1;
    if (!chan->open) {
        PyErr_SetString(ChannelClosedError, "channel already closed");
        goto done;
849
    }
850

851
    if (_channelends_close_interpreter(chan->ends, interp, end) != 0) {
852 853 854 855 856 857 858 859
        goto done;
    }
    chan->open = _channelends_is_open(chan->ends);

    res = 0;
done:
    PyThread_release_lock(chan->mutex);
    return res;
860 861
}

862
static int
863
_channel_close_all(_PyChannelState *chan, int end, int force)
864
{
865
    int res = -1;
866 867
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);

868 869 870 871 872
    if (!chan->open) {
        PyErr_SetString(ChannelClosedError, "channel already closed");
        goto done;
    }

873 874 875 876 877 878
    if (!force && chan->queue->count > 0) {
        PyErr_SetString(ChannelNotEmptyError,
                        "may not be closed if not empty (try force=True)");
        goto done;
    }

879 880 881 882
    chan->open = 0;

    // We *could* also just leave these in place, since we've marked
    // the channel as closed already.
883
    _channelends_close_all(chan->ends, end, force);
884 885 886 887 888

    res = 0;
done:
    PyThread_release_lock(chan->mutex);
    return res;
889 890
}

891 892
/* the set of channels */

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
struct _channelref;

typedef struct _channelref {
    int64_t id;
    _PyChannelState *chan;
    struct _channelref *next;
    Py_ssize_t objcount;
} _channelref;

static _channelref *
_channelref_new(int64_t id, _PyChannelState *chan)
{
    _channelref *ref = PyMem_NEW(_channelref, 1);
    if (ref == NULL) {
        return NULL;
    }
    ref->id = id;
    ref->chan = chan;
    ref->next = NULL;
    ref->objcount = 0;
    return ref;
}

916 917 918 919 920 921 922 923 924 925 926 927
//static void
//_channelref_clear(_channelref *ref)
//{
//    ref->id = -1;
//    ref->chan = NULL;
//    ref->next = NULL;
//    ref->objcount = 0;
//}

static void
_channelref_free(_channelref *ref)
{
928 929 930
    if (ref->chan != NULL) {
        _channel_clear_closing(ref->chan);
    }
931 932 933 934
    //_channelref_clear(ref);
    PyMem_Free(ref);
}

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
static _channelref *
_channelref_find(_channelref *first, int64_t id, _channelref **pprev)
{
    _channelref *prev = NULL;
    _channelref *ref = first;
    while (ref != NULL) {
        if (ref->id == id) {
            break;
        }
        prev = ref;
        ref = ref->next;
    }
    if (pprev != NULL) {
        *pprev = prev;
    }
    return ref;
}

typedef struct _channels {
    PyThread_type_lock mutex;
    _channelref *head;
    int64_t numopen;
    int64_t next_id;
} _channels;

static int
_channels_init(_channels *channels)
{
    if (channels->mutex == NULL) {
        channels->mutex = PyThread_allocate_lock();
        if (channels->mutex == NULL) {
            PyErr_SetString(ChannelError,
                            "can't initialize mutex for channel management");
            return -1;
        }
    }
    channels->head = NULL;
    channels->numopen = 0;
    channels->next_id = 0;
    return 0;
}

static int64_t
_channels_next_id(_channels *channels)  // needs lock
{
    int64_t id = channels->next_id;
    if (id < 0) {
        /* overflow */
        PyErr_SetString(ChannelError,
                        "failed to get a channel ID");
        return -1;
    }
    channels->next_id += 1;
    return id;
}

static _PyChannelState *
_channels_lookup(_channels *channels, int64_t id, PyThread_type_lock *pmutex)
{
    _PyChannelState *chan = NULL;
    PyThread_acquire_lock(channels->mutex, WAIT_LOCK);
    if (pmutex != NULL) {
        *pmutex = NULL;
    }

    _channelref *ref = _channelref_find(channels->head, id, NULL);
    if (ref == NULL) {
1002
        PyErr_Format(ChannelNotFoundError, "channel %" PRId64 " not found", id);
1003 1004 1005
        goto done;
    }
    if (ref->chan == NULL || !ref->chan->open) {
1006
        PyErr_Format(ChannelClosedError, "channel %" PRId64 " closed", id);
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        goto done;
    }

    if (pmutex != NULL) {
        // The mutex will be closed by the caller.
        *pmutex = channels->mutex;
    }

    chan = ref->chan;
done:
    if (pmutex == NULL || *pmutex == NULL) {
        PyThread_release_lock(channels->mutex);
    }
    return chan;
}

static int64_t
_channels_add(_channels *channels, _PyChannelState *chan)
{
    int64_t cid = -1;
    PyThread_acquire_lock(channels->mutex, WAIT_LOCK);

    // Create a new ref.
    int64_t id = _channels_next_id(channels);
    if (id < 0) {
        goto done;
    }
    _channelref *ref = _channelref_new(id, chan);
    if (ref == NULL) {
        goto done;
    }

    // Add it to the list.
    // We assume that the channel is a new one (not already in the list).
    ref->next = channels->head;
    channels->head = ref;
    channels->numopen += 1;

    cid = id;
done:
    PyThread_release_lock(channels->mutex);
    return cid;
}

1051 1052 1053
/* forward */
static int _channel_set_closing(struct _channelref *, PyThread_type_lock);

1054
static int
1055 1056
_channels_close(_channels *channels, int64_t cid, _PyChannelState **pchan,
                int end, int force)
1057 1058 1059 1060 1061 1062 1063 1064 1065
{
    int res = -1;
    PyThread_acquire_lock(channels->mutex, WAIT_LOCK);
    if (pchan != NULL) {
        *pchan = NULL;
    }

    _channelref *ref = _channelref_find(channels->head, cid, NULL);
    if (ref == NULL) {
1066
        PyErr_Format(ChannelNotFoundError, "channel %" PRId64 " not found", cid);
1067 1068 1069 1070
        goto done;
    }

    if (ref->chan == NULL) {
1071
        PyErr_Format(ChannelClosedError, "channel %" PRId64 " closed", cid);
1072 1073
        goto done;
    }
1074
    else if (!force && end == CHANNEL_SEND && ref->chan->closing != NULL) {
1075
        PyErr_Format(ChannelClosedError, "channel %" PRId64 " closed", cid);
1076 1077
        goto done;
    }
1078
    else {
1079 1080 1081 1082
        if (_channel_close_all(ref->chan, end, force) != 0) {
            if (end == CHANNEL_SEND &&
                    PyErr_ExceptionMatches(ChannelNotEmptyError)) {
                if (ref->chan->closing != NULL) {
1083
                    PyErr_Format(ChannelClosedError,
1084
                                 "channel %" PRId64 " closed", cid);
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
                    goto done;
                }
                // Mark the channel as closing and return.  The channel
                // will be cleaned up in _channel_next().
                PyErr_Clear();
                if (_channel_set_closing(ref, channels->mutex) != 0) {
                    goto done;
                }
                if (pchan != NULL) {
                    *pchan = ref->chan;
                }
                res = 0;
            }
1098 1099 1100 1101 1102
            goto done;
        }
        if (pchan != NULL) {
            *pchan = ref->chan;
        }
1103
        else  {
1104 1105
            _channel_free(ref->chan);
        }
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
        ref->chan = NULL;
    }

    res = 0;
done:
    PyThread_release_lock(channels->mutex);
    return res;
}

static void
_channels_remove_ref(_channels *channels, _channelref *ref, _channelref *prev,
                     _PyChannelState **pchan)
{
    if (ref == channels->head) {
        channels->head = ref->next;
    }
    else {
        prev->next = ref->next;
    }
    channels->numopen -= 1;

    if (pchan != NULL) {
        *pchan = ref->chan;
    }
1130
    _channelref_free(ref);
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
}

static int
_channels_remove(_channels *channels, int64_t id, _PyChannelState **pchan)
{
    int res = -1;
    PyThread_acquire_lock(channels->mutex, WAIT_LOCK);

    if (pchan != NULL) {
        *pchan = NULL;
    }

    _channelref *prev = NULL;
    _channelref *ref = _channelref_find(channels->head, id, &prev);
    if (ref == NULL) {
1146
        PyErr_Format(ChannelNotFoundError, "channel %" PRId64 " not found", id);
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        goto done;
    }

    _channels_remove_ref(channels, ref, prev, pchan);

    res = 0;
done:
    PyThread_release_lock(channels->mutex);
    return res;
}

static int
_channels_add_id_object(_channels *channels, int64_t id)
{
    int res = -1;
    PyThread_acquire_lock(channels->mutex, WAIT_LOCK);

    _channelref *ref = _channelref_find(channels->head, id, NULL);
    if (ref == NULL) {
1166
        PyErr_Format(ChannelNotFoundError, "channel %" PRId64 " not found", id);
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
        goto done;
    }
    ref->objcount += 1;

    res = 0;
done:
    PyThread_release_lock(channels->mutex);
    return res;
}

static void
_channels_drop_id_object(_channels *channels, int64_t id)
{
    PyThread_acquire_lock(channels->mutex, WAIT_LOCK);

    _channelref *prev = NULL;
    _channelref *ref = _channelref_find(channels->head, id, &prev);
    if (ref == NULL) {
        // Already destroyed.
        goto done;
    }
    ref->objcount -= 1;

    // Destroy if no longer used.
    if (ref->objcount == 0) {
        _PyChannelState *chan = NULL;
        _channels_remove_ref(channels, ref, prev, &chan);
        if (chan != NULL) {
            _channel_free(chan);
        }
    }

done:
    PyThread_release_lock(channels->mutex);
}

1203
static int64_t *
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
_channels_list_all(_channels *channels, int64_t *count)
{
    int64_t *cids = NULL;
    PyThread_acquire_lock(channels->mutex, WAIT_LOCK);
    int64_t numopen = channels->numopen;
    if (numopen >= PY_SSIZE_T_MAX) {
        PyErr_SetString(PyExc_RuntimeError, "too many channels open");
        goto done;
    }
    int64_t *ids = PyMem_NEW(int64_t, (Py_ssize_t)(channels->numopen));
    if (ids == NULL) {
        goto done;
    }
    _channelref *ref = channels->head;
    for (int64_t i=0; ref != NULL; ref = ref->next, i++) {
        ids[i] = ref->id;
    }
    *count = channels->numopen;

    cids = ids;
done:
    PyThread_release_lock(channels->mutex);
    return cids;
}

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
/* support for closing non-empty channels */

struct _channel_closing {
    struct _channelref *ref;
};

static int
_channel_set_closing(struct _channelref *ref, PyThread_type_lock mutex) {
    struct _channel *chan = ref->chan;
    if (chan == NULL) {
        // already closed
        return 0;
    }
    int res = -1;
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);
    if (chan->closing != NULL) {
        PyErr_SetString(ChannelClosedError, "channel closed");
        goto done;
    }
    chan->closing = PyMem_NEW(struct _channel_closing, 1);
    if (chan->closing == NULL) {
        goto done;
    }
    chan->closing->ref = ref;

    res = 0;
done:
    PyThread_release_lock(chan->mutex);
    return res;
}

static void
_channel_clear_closing(struct _channel *chan) {
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);
    if (chan->closing != NULL) {
        PyMem_Free(chan->closing);
        chan->closing = NULL;
    }
    PyThread_release_lock(chan->mutex);
}

static void
_channel_finish_closing(struct _channel *chan) {
    struct _channel_closing *closing = chan->closing;
    if (closing == NULL) {
        return;
    }
    _channelref *ref = closing->ref;
    _channel_clear_closing(chan);
    // Do the things that would have been done in _channels_close().
    ref->chan = NULL;
    _channel_free(chan);
};

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
/* "high"-level channel-related functions */

static int64_t
_channel_create(_channels *channels)
{
    _PyChannelState *chan = _channel_new();
    if (chan == NULL) {
        return -1;
    }
    int64_t id = _channels_add(channels, chan);
    if (id < 0) {
        _channel_free(chan);
        return -1;
    }
    return id;
}

static int
_channel_destroy(_channels *channels, int64_t id)
{
    _PyChannelState *chan = NULL;
    if (_channels_remove(channels, id, &chan) != 0) {
        return -1;
    }
    if (chan != NULL) {
        _channel_free(chan);
    }
    return 0;
}

static int
_channel_send(_channels *channels, int64_t id, PyObject *obj)
{
    PyInterpreterState *interp = _get_current();
    if (interp == NULL) {
        return -1;
    }

    // Look up the channel.
    PyThread_type_lock mutex = NULL;
    _PyChannelState *chan = _channels_lookup(channels, id, &mutex);
    if (chan == NULL) {
        return -1;
    }
    // Past this point we are responsible for releasing the mutex.

1329
    if (chan->closing != NULL) {
1330
        PyErr_Format(ChannelClosedError, "channel %" PRId64 " closed", id);
1331 1332 1333 1334
        PyThread_release_lock(mutex);
        return -1;
    }

1335 1336 1337 1338 1339 1340 1341
    // Convert the object to cross-interpreter data.
    _PyCrossInterpreterData *data = PyMem_NEW(_PyCrossInterpreterData, 1);
    if (data == NULL) {
        PyThread_release_lock(mutex);
        return -1;
    }
    if (_PyObject_GetCrossInterpreterData(obj, data) != 0) {
1342
        PyMem_Free(data);
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        PyThread_release_lock(mutex);
        return -1;
    }

    // Add the data to the channel.
    int res = _channel_add(chan, interp->id, data);
    PyThread_release_lock(mutex);
    if (res != 0) {
        _PyCrossInterpreterData_Release(data);
        PyMem_Free(data);
        return -1;
    }

    return 0;
}

static PyObject *
_channel_recv(_channels *channels, int64_t id)
{
    PyInterpreterState *interp = _get_current();
    if (interp == NULL) {
        return NULL;
    }

    // Look up the channel.
    PyThread_type_lock mutex = NULL;
    _PyChannelState *chan = _channels_lookup(channels, id, &mutex);
    if (chan == NULL) {
        return NULL;
    }
    // Past this point we are responsible for releasing the mutex.

    // Pop off the next item from the channel.
    _PyCrossInterpreterData *data = _channel_next(chan, interp->id);
    PyThread_release_lock(mutex);
    if (data == NULL) {
1379
        if (!PyErr_Occurred()) {
1380
            PyErr_Format(ChannelEmptyError, "channel %" PRId64 " is empty", id);
1381
        }
1382 1383 1384 1385 1386 1387 1388 1389 1390
        return NULL;
    }

    // Convert the data back to an object.
    PyObject *obj = _PyCrossInterpreterData_NewObject(data);
    if (obj == NULL) {
        return NULL;
    }
    _PyCrossInterpreterData_Release(data);
1391
    PyMem_Free(data);
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412

    return obj;
}

static int
_channel_drop(_channels *channels, int64_t id, int send, int recv)
{
    PyInterpreterState *interp = _get_current();
    if (interp == NULL) {
        return -1;
    }

    // Look up the channel.
    PyThread_type_lock mutex = NULL;
    _PyChannelState *chan = _channels_lookup(channels, id, &mutex);
    if (chan == NULL) {
        return -1;
    }
    // Past this point we are responsible for releasing the mutex.

    // Close one or both of the two ends.
1413
    int res = _channel_close_interpreter(chan, interp->id, send-recv);
1414 1415 1416 1417 1418
    PyThread_release_lock(mutex);
    return res;
}

static int
1419
_channel_close(_channels *channels, int64_t id, int end, int force)
1420
{
1421
    return _channels_close(channels, id, NULL, end, force);
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
}

/* ChannelID class */

static PyTypeObject ChannelIDtype;

typedef struct channelid {
    PyObject_HEAD
    int64_t id;
    int end;
1432
    int resolve;
1433 1434 1435 1436 1437
    _channels *channels;
} channelid;

static channelid *
newchannelid(PyTypeObject *cls, int64_t cid, int end, _channels *channels,
1438
             int force, int resolve)
1439 1440 1441 1442 1443 1444 1445
{
    channelid *self = PyObject_New(channelid, cls);
    if (self == NULL) {
        return NULL;
    }
    self->id = cid;
    self->end = end;
1446
    self->resolve = resolve;
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
    self->channels = channels;

    if (_channels_add_id_object(channels, cid) != 0) {
        if (force && PyErr_ExceptionMatches(ChannelNotFoundError)) {
            PyErr_Clear();
        }
        else {
            Py_DECREF((PyObject *)self);
            return NULL;
        }
    }

    return self;
}

static _channels * _global_channels(void);

static PyObject *
channelid_new(PyTypeObject *cls, PyObject *args, PyObject *kwds)
{
1467
    static char *kwlist[] = {"id", "send", "recv", "force", "_resolve", NULL};
1468 1469 1470 1471
    PyObject *id;
    int send = -1;
    int recv = -1;
    int force = 0;
1472
    int resolve = 0;
1473
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
1474 1475
                                     "O|$pppp:ChannelID.__new__", kwlist,
                                     &id, &send, &recv, &force, &resolve))
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
        return NULL;

    // Coerce and check the ID.
    int64_t cid;
    if (PyObject_TypeCheck(id, &ChannelIDtype)) {
        cid = ((channelid *)id)->id;
    }
    else {
        cid = _coerce_id(id);
        if (cid < 0) {
            return NULL;
        }
    }

    // Handle "send" and "recv".
    if (send == 0 && recv == 0) {
        PyErr_SetString(PyExc_ValueError,
                        "'send' and 'recv' cannot both be False");
        return NULL;
    }
1496

1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
    int end = 0;
    if (send == 1) {
        if (recv == 0 || recv == -1) {
            end = CHANNEL_SEND;
        }
    }
    else if (recv == 1) {
        end = CHANNEL_RECV;
    }

1507 1508
    return (PyObject *)newchannelid(cls, cid, end, _global_channels(),
                                    force, resolve);
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
}

static void
channelid_dealloc(PyObject *v)
{
    int64_t cid = ((channelid *)v)->id;
    _channels *channels = ((channelid *)v)->channels;
    Py_TYPE(v)->tp_free(v);

    _channels_drop_id_object(channels, cid);
}

static PyObject *
channelid_repr(PyObject *self)
{
    PyTypeObject *type = Py_TYPE(self);
    const char *name = _PyType_Name(type);

    channelid *cid = (channelid *)self;
    const char *fmt;
    if (cid->end == CHANNEL_SEND) {
1530
        fmt = "%s(%" PRId64 ", send=True)";
1531 1532
    }
    else if (cid->end == CHANNEL_RECV) {
1533
        fmt = "%s(%" PRId64 ", recv=True)";
1534 1535
    }
    else {
1536
        fmt = "%s(%" PRId64 ")";
1537 1538 1539 1540
    }
    return PyUnicode_FromFormat(fmt, name, cid->id);
}

1541 1542 1543 1544
static PyObject *
channelid_str(PyObject *self)
{
    channelid *cid = (channelid *)self;
1545
    return PyUnicode_FromFormat("%" PRId64 "", cid->id);
1546 1547
}

1548
static PyObject *
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
channelid_int(PyObject *self)
{
    channelid *cid = (channelid *)self;
    return PyLong_FromLongLong(cid->id);
}

static PyNumberMethods channelid_as_number = {
     0,                        /* nb_add */
     0,                        /* nb_subtract */
     0,                        /* nb_multiply */
     0,                        /* nb_remainder */
     0,                        /* nb_divmod */
     0,                        /* nb_power */
     0,                        /* nb_negative */
     0,                        /* nb_positive */
     0,                        /* nb_absolute */
     0,                        /* nb_bool */
     0,                        /* nb_invert */
     0,                        /* nb_lshift */
     0,                        /* nb_rshift */
     0,                        /* nb_and */
     0,                        /* nb_xor */
     0,                        /* nb_or */
     (unaryfunc)channelid_int, /* nb_int */
     0,                        /* nb_reserved */
     0,                        /* nb_float */

     0,                        /* nb_inplace_add */
     0,                        /* nb_inplace_subtract */
     0,                        /* nb_inplace_multiply */
     0,                        /* nb_inplace_remainder */
     0,                        /* nb_inplace_power */
     0,                        /* nb_inplace_lshift */
     0,                        /* nb_inplace_rshift */
     0,                        /* nb_inplace_and */
     0,                        /* nb_inplace_xor */
     0,                        /* nb_inplace_or */

     0,                        /* nb_floor_divide */
     0,                        /* nb_true_divide */
     0,                        /* nb_inplace_floor_divide */
     0,                        /* nb_inplace_true_divide */

     (unaryfunc)channelid_int, /* nb_index */
};

static Py_hash_t
channelid_hash(PyObject *self)
{
    channelid *cid = (channelid *)self;
    PyObject *id = PyLong_FromLongLong(cid->id);
    if (id == NULL) {
        return -1;
    }
1603 1604 1605
    Py_hash_t hash = PyObject_Hash(id);
    Py_DECREF(id);
    return hash;
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
}

static PyObject *
channelid_richcompare(PyObject *self, PyObject *other, int op)
{
    if (op != Py_EQ && op != Py_NE) {
        Py_RETURN_NOTIMPLEMENTED;
    }

    if (!PyObject_TypeCheck(self, &ChannelIDtype)) {
        Py_RETURN_NOTIMPLEMENTED;
    }

    channelid *cid = (channelid *)self;
    int equal;
    if (PyObject_TypeCheck(other, &ChannelIDtype)) {
        channelid *othercid = (channelid *)other;
        if (cid->end != othercid->end) {
            equal = 0;
        }
        else {
            equal = (cid->id == othercid->id);
        }
    }
    else {
        other = PyNumber_Long(other);
        if (other == NULL) {
            PyErr_Clear();
            Py_RETURN_NOTIMPLEMENTED;
        }
        int64_t othercid = PyLong_AsLongLong(other);
1637
        Py_DECREF(other);
1638 1639 1640
        if (othercid == -1 && PyErr_Occurred() != NULL) {
            return NULL;
        }
1641
        if (othercid < 0) {
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
            equal = 0;
        }
        else {
            equal = (cid->id == othercid);
        }
    }

    if ((op == Py_EQ && equal) || (op == Py_NE && !equal)) {
        Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
}

1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
static PyObject *
_channel_from_cid(PyObject *cid, int end)
{
    PyObject *highlevel = PyImport_ImportModule("interpreters");
    if (highlevel == NULL) {
        PyErr_Clear();
        highlevel = PyImport_ImportModule("test.support.interpreters");
        if (highlevel == NULL) {
            return NULL;
        }
    }
    const char *clsname = (end == CHANNEL_RECV) ? "RecvChannel" :
                                                  "SendChannel";
    PyObject *cls = PyObject_GetAttrString(highlevel, clsname);
    Py_DECREF(highlevel);
    if (cls == NULL) {
        return NULL;
    }
    PyObject *chan = PyObject_CallFunctionObjArgs(cls, cid, NULL);
    Py_DECREF(cls);
    if (chan == NULL) {
        return NULL;
    }
    return chan;
}

1681 1682 1683
struct _channelid_xid {
    int64_t id;
    int end;
1684
    int resolve;
1685 1686 1687 1688 1689 1690
};

static PyObject *
_channelid_from_xid(_PyCrossInterpreterData *data)
{
    struct _channelid_xid *xid = (struct _channelid_xid *)data->data;
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
    // Note that we do not preserve the "resolve" flag.
    PyObject *cid = (PyObject *)newchannelid(&ChannelIDtype, xid->id, xid->end,
                                             _global_channels(), 0, 0);
    if (xid->end == 0) {
        return cid;
    }
    if (!xid->resolve) {
        return cid;
    }

    /* Try returning a high-level channel end but fall back to the ID. */
1702
    PyObject *chan = _channel_from_cid(cid, xid->end);
1703
    if (chan == NULL) {
1704 1705
        PyErr_Clear();
        return cid;
1706 1707 1708
    }
    Py_DECREF(cid);
    return chan;
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
}

static int
_channelid_shared(PyObject *obj, _PyCrossInterpreterData *data)
{
    struct _channelid_xid *xid = PyMem_NEW(struct _channelid_xid, 1);
    if (xid == NULL) {
        return -1;
    }
    xid->id = ((channelid *)obj)->id;
    xid->end = ((channelid *)obj)->end;
1720
    xid->resolve = ((channelid *)obj)->resolve;
1721 1722

    data->data = xid;
1723
    Py_INCREF(obj);
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
    data->obj = obj;
    data->new_object = _channelid_from_xid;
    data->free = PyMem_Free;
    return 0;
}

static PyObject *
channelid_end(PyObject *self, void *end)
{
    int force = 1;
    channelid *cid = (channelid *)self;
    if (end != NULL) {
        return (PyObject *)newchannelid(Py_TYPE(self), cid->id, *(int *)end,
1737
                                        cid->channels, force, cid->resolve);
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
    }

    if (cid->end == CHANNEL_SEND) {
        return PyUnicode_InternFromString("send");
    }
    if (cid->end == CHANNEL_RECV) {
        return PyUnicode_InternFromString("recv");
    }
    return PyUnicode_InternFromString("both");
}

static int _channelid_end_send = CHANNEL_SEND;
static int _channelid_end_recv = CHANNEL_RECV;

static PyGetSetDef channelid_getsets[] = {
    {"end", (getter)channelid_end, NULL,
     PyDoc_STR("'send', 'recv', or 'both'")},
    {"send", (getter)channelid_end, NULL,
     PyDoc_STR("the 'send' end of the channel"), &_channelid_end_send},
    {"recv", (getter)channelid_end, NULL,
     PyDoc_STR("the 'recv' end of the channel"), &_channelid_end_recv},
    {NULL}
};

PyDoc_STRVAR(channelid_doc,
"A channel ID identifies a channel and may be used as an int.");

static PyTypeObject ChannelIDtype = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "_xxsubinterpreters.ChannelID", /* tp_name */
1768
    sizeof(channelid),              /* tp_basicsize */
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
    0,                              /* tp_itemsize */
    (destructor)channelid_dealloc,  /* tp_dealloc */
    0,                              /* tp_print */
    0,                              /* tp_getattr */
    0,                              /* tp_setattr */
    0,                              /* tp_as_async */
    (reprfunc)channelid_repr,       /* tp_repr */
    &channelid_as_number,           /* tp_as_number */
    0,                              /* tp_as_sequence */
    0,                              /* tp_as_mapping */
    channelid_hash,                 /* tp_hash */
    0,                              /* tp_call */
1781
    (reprfunc)channelid_str,        /* tp_str */
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
    0,                              /* tp_getattro */
    0,                              /* tp_setattro */
    0,                              /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
        Py_TPFLAGS_LONG_SUBCLASS,   /* tp_flags */
    channelid_doc,                  /* tp_doc */
    0,                              /* tp_traverse */
    0,                              /* tp_clear */
    channelid_richcompare,          /* tp_richcompare */
    0,                              /* tp_weaklistoffset */
    0,                              /* tp_iter */
    0,                              /* tp_iternext */
    0,                              /* tp_methods */
    0,                              /* tp_members */
    channelid_getsets,              /* tp_getset */
    0,                              /* tp_base */
    0,                              /* tp_dict */
    0,                              /* tp_descr_get */
    0,                              /* tp_descr_set */
    0,                              /* tp_dictoffset */
    0,                              /* tp_init */
    0,                              /* tp_alloc */
    // Note that we do not set tp_new to channelid_new.  Instead we
    // set it to NULL, meaning it cannot be instantiated from Python
    // code.  We do this because there is a strong relationship between
    // channel IDs and the channel lifecycle, so this limitation avoids
    // related complications.
    NULL,                           /* tp_new */
};

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835

/* interpreter-specific code ************************************************/

static PyObject * RunFailedError = NULL;

static int
interp_exceptions_init(PyObject *ns)
{
    // XXX Move the exceptions into per-module memory?

    if (RunFailedError == NULL) {
        // An uncaught exception came out of interp_run_string().
        RunFailedError = PyErr_NewException("_xxsubinterpreters.RunFailedError",
                                            PyExc_RuntimeError, NULL);
        if (RunFailedError == NULL) {
            return -1;
        }
        if (PyDict_SetItemString(ns, "RunFailedError", RunFailedError) != 0) {
            return -1;
        }
    }

    return 0;
}
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871

static int
_is_running(PyInterpreterState *interp)
{
    PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
    if (PyThreadState_Next(tstate) != NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "interpreter has more than one thread");
        return -1;
    }
    PyFrameObject *frame = tstate->frame;
    if (frame == NULL) {
        if (PyErr_Occurred() != NULL) {
            return -1;
        }
        return 0;
    }
    return (int)(frame->f_executing);
}

static int
_ensure_not_running(PyInterpreterState *interp)
{
    int is_running = _is_running(interp);
    if (is_running < 0) {
        return -1;
    }
    if (is_running) {
        PyErr_Format(PyExc_RuntimeError, "interpreter already running");
        return -1;
    }
    return 0;
}

static int
_run_script(PyInterpreterState *interp, const char *codestr,
1872
            _sharedns *shared, _sharedexception **exc)
1873
{
1874 1875 1876 1877
    PyObject *exctype = NULL;
    PyObject *excval = NULL;
    PyObject *tb = NULL;

1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
    PyObject *main_mod = PyMapping_GetItemString(interp->modules, "__main__");
    if (main_mod == NULL) {
        goto error;
    }
    PyObject *ns = PyModule_GetDict(main_mod);  // borrowed
    Py_DECREF(main_mod);
    if (ns == NULL) {
        goto error;
    }
    Py_INCREF(ns);

    // Apply the cross-interpreter data.
    if (shared != NULL) {
1891 1892 1893
        if (_sharedns_apply(shared, ns) != 0) {
            Py_DECREF(ns);
            goto error;
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
        }
    }

    // Run the string (see PyRun_SimpleStringFlags).
    PyObject *result = PyRun_StringFlags(codestr, Py_file_input, ns, ns, NULL);
    Py_DECREF(ns);
    if (result == NULL) {
        goto error;
    }
    else {
        Py_DECREF(result);  // We throw away the result.
    }

1907
    *exc = NULL;
1908 1909 1910
    return 0;

error:
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
    PyErr_Fetch(&exctype, &excval, &tb);

    _sharedexception *sharedexc = _sharedexception_bind(exctype, excval, tb);
    Py_XDECREF(exctype);
    Py_XDECREF(excval);
    Py_XDECREF(tb);
    if (sharedexc == NULL) {
        fprintf(stderr, "RunFailedError: script raised an uncaught exception");
        PyErr_Clear();
        sharedexc = NULL;
    }
    else {
        assert(!PyErr_Occurred());
    }
    *exc = sharedexc;
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
    return -1;
}

static int
_run_script_in_interpreter(PyInterpreterState *interp, const char *codestr,
                           PyObject *shareables)
{
    if (_ensure_not_running(interp) < 0) {
        return -1;
    }

1937
    _sharedns *shared = _get_shared_ns(shareables);
1938 1939 1940 1941 1942
    if (shared == NULL && PyErr_Occurred()) {
        return -1;
    }

    // Switch to interpreter.
1943
    PyThreadState *save_tstate = NULL;
1944
    if (interp != _PyInterpreterState_Get()) {
1945 1946 1947 1948 1949
        // XXX Using the "head" thread isn't strictly correct.
        PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
        // XXX Possible GILState issues?
        save_tstate = PyThreadState_Swap(tstate);
    }
1950 1951 1952

    // Run the script.
    _sharedexception *exc = NULL;
1953
    int result = _run_script(interp, codestr, shared, &exc);
1954 1955 1956 1957 1958 1959 1960 1961

    // Switch back.
    if (save_tstate != NULL) {
        PyThreadState_Swap(save_tstate);
    }

    // Propagate any exception out to the caller.
    if (exc != NULL) {
1962 1963
        _sharedexception_apply(exc, RunFailedError);
        _sharedexception_free(exc);
1964 1965 1966 1967 1968 1969 1970
    }
    else if (result != 0) {
        // We were unable to allocate a shared exception.
        PyErr_NoMemory();
    }

    if (shared != NULL) {
1971
        _sharedns_free(shared);
1972 1973 1974 1975 1976
    }

    return result;
}

1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
/* InterpreterID class */

static PyTypeObject InterpreterIDtype;

typedef struct interpid {
    PyObject_HEAD
    int64_t id;
} interpid;

static interpid *
newinterpid(PyTypeObject *cls, int64_t id, int force)
{
    PyInterpreterState *interp = _PyInterpreterState_LookUpID(id);
    if (interp == NULL) {
        if (force) {
            PyErr_Clear();
        }
        else {
            return NULL;
        }
    }

    interpid *self = PyObject_New(interpid, cls);
    if (self == NULL) {
        return NULL;
    }
    self->id = id;

    if (interp != NULL) {
        _PyInterpreterState_IDIncref(interp);
    }
    return self;
}

static PyObject *
interpid_new(PyTypeObject *cls, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {"id", "force", NULL};
    PyObject *idobj;
    int force = 0;
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                                     "O|$p:InterpreterID.__init__", kwlist,
                                     &idobj, &force)) {
        return NULL;
    }

    // Coerce and check the ID.
    int64_t id;
    if (PyObject_TypeCheck(idobj, &InterpreterIDtype)) {
        id = ((interpid *)idobj)->id;
    }
    else {
        id = _coerce_id(idobj);
        if (id < 0) {
            return NULL;
        }
    }

    return (PyObject *)newinterpid(cls, id, force);
}

static void
interpid_dealloc(PyObject *v)
{
    int64_t id = ((interpid *)v)->id;
    PyInterpreterState *interp = _PyInterpreterState_LookUpID(id);
    if (interp != NULL) {
        _PyInterpreterState_IDDecref(interp);
    }
    else {
        // already deleted
        PyErr_Clear();
    }
    Py_TYPE(v)->tp_free(v);
}

static PyObject *
interpid_repr(PyObject *self)
{
    PyTypeObject *type = Py_TYPE(self);
    const char *name = _PyType_Name(type);
    interpid *id = (interpid *)self;
2059
    return PyUnicode_FromFormat("%s(%" PRId64 ")", name, id->id);
2060 2061
}

2062 2063 2064 2065
static PyObject *
interpid_str(PyObject *self)
{
    interpid *id = (interpid *)self;
2066
    return PyUnicode_FromFormat("%" PRId64 "", id->id);
2067 2068
}

2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
PyObject *
interpid_int(PyObject *self)
{
    interpid *id = (interpid *)self;
    return PyLong_FromLongLong(id->id);
}

static PyNumberMethods interpid_as_number = {
     0,                       /* nb_add */
     0,                       /* nb_subtract */
     0,                       /* nb_multiply */
     0,                       /* nb_remainder */
     0,                       /* nb_divmod */
     0,                       /* nb_power */
     0,                       /* nb_negative */
     0,                       /* nb_positive */
     0,                       /* nb_absolute */
     0,                       /* nb_bool */
     0,                       /* nb_invert */
     0,                       /* nb_lshift */
     0,                       /* nb_rshift */
     0,                       /* nb_and */
     0,                       /* nb_xor */
     0,                       /* nb_or */
     (unaryfunc)interpid_int, /* nb_int */
     0,                       /* nb_reserved */
     0,                       /* nb_float */

     0,                       /* nb_inplace_add */
     0,                       /* nb_inplace_subtract */
     0,                       /* nb_inplace_multiply */
     0,                       /* nb_inplace_remainder */
     0,                       /* nb_inplace_power */
     0,                       /* nb_inplace_lshift */
     0,                       /* nb_inplace_rshift */
     0,                       /* nb_inplace_and */
     0,                       /* nb_inplace_xor */
     0,                       /* nb_inplace_or */

     0,                       /* nb_floor_divide */
     0,                       /* nb_true_divide */
     0,                       /* nb_inplace_floor_divide */
     0,                       /* nb_inplace_true_divide */

     (unaryfunc)interpid_int, /* nb_index */
};

static Py_hash_t
interpid_hash(PyObject *self)
{
    interpid *id = (interpid *)self;
    PyObject *obj = PyLong_FromLongLong(id->id);
    if (obj == NULL) {
        return -1;
    }
    Py_hash_t hash = PyObject_Hash(obj);
    Py_DECREF(obj);
    return hash;
}

static PyObject *
interpid_richcompare(PyObject *self, PyObject *other, int op)
{
    if (op != Py_EQ && op != Py_NE) {
        Py_RETURN_NOTIMPLEMENTED;
    }

    if (!PyObject_TypeCheck(self, &InterpreterIDtype)) {
        Py_RETURN_NOTIMPLEMENTED;
    }

    interpid *id = (interpid *)self;
    int equal;
    if (PyObject_TypeCheck(other, &InterpreterIDtype)) {
        interpid *otherid = (interpid *)other;
        equal = (id->id == otherid->id);
    }
    else {
        other = PyNumber_Long(other);
        if (other == NULL) {
            PyErr_Clear();
            Py_RETURN_NOTIMPLEMENTED;
        }
        int64_t otherid = PyLong_AsLongLong(other);
        Py_DECREF(other);
        if (otherid == -1 && PyErr_Occurred() != NULL) {
            return NULL;
        }
        if (otherid < 0) {
            equal = 0;
        }
        else {
            equal = (id->id == otherid);
        }
    }

    if ((op == Py_EQ && equal) || (op == Py_NE && !equal)) {
        Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
}

PyDoc_STRVAR(interpid_doc,
"A interpreter ID identifies a interpreter and may be used as an int.");

static PyTypeObject InterpreterIDtype = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "interpreters.InterpreterID",   /* tp_name */
2177
    sizeof(interpid),               /* tp_basicsize */
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
    0,                              /* tp_itemsize */
    (destructor)interpid_dealloc,   /* tp_dealloc */
    0,                              /* tp_print */
    0,                              /* tp_getattr */
    0,                              /* tp_setattr */
    0,                              /* tp_as_async */
    (reprfunc)interpid_repr,        /* tp_repr */
    &interpid_as_number,            /* tp_as_number */
    0,                              /* tp_as_sequence */
    0,                              /* tp_as_mapping */
    interpid_hash,                  /* tp_hash */
    0,                              /* tp_call */
2190
    (reprfunc)interpid_str,         /* tp_str */
2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
    0,                              /* tp_getattro */
    0,                              /* tp_setattro */
    0,                              /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
        Py_TPFLAGS_LONG_SUBCLASS,   /* tp_flags */
    interpid_doc,                   /* tp_doc */
    0,                              /* tp_traverse */
    0,                              /* tp_clear */
    interpid_richcompare,           /* tp_richcompare */
    0,                              /* tp_weaklistoffset */
    0,                              /* tp_iter */
    0,                              /* tp_iternext */
    0,                              /* tp_methods */
    0,                              /* tp_members */
    0,                              /* tp_getset */
    0,                              /* tp_base */
    0,                              /* tp_dict */
    0,                              /* tp_descr_get */
    0,                              /* tp_descr_set */
    0,                              /* tp_dictoffset */
    0,                              /* tp_init */
    0,                              /* tp_alloc */
    interpid_new,                   /* tp_new */
};

static PyObject *
_get_id(PyInterpreterState *interp)
{
    PY_INT64_T id = PyInterpreterState_GetID(interp);
    if (id < 0) {
        return NULL;
    }
    return (PyObject *)newinterpid(&InterpreterIDtype, id, 0);
}

static PyInterpreterState *
_look_up(PyObject *requested_id)
{
    int64_t id;
    if (PyObject_TypeCheck(requested_id, &InterpreterIDtype)) {
        id = ((interpid *)requested_id)->id;
    }
    else {
        id = PyLong_AsLongLong(requested_id);
        if (id == -1 && PyErr_Occurred() != NULL) {
            return NULL;
        }
        assert(id <= INT64_MAX);
    }
    return _PyInterpreterState_LookUpID(id);
}

2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274

/* module level code ********************************************************/

/* globals is the process-global state for the module.  It holds all
   the data that we need to share between interpreters, so it cannot
   hold PyObject values. */
static struct globals {
    _channels channels;
} _globals = {{0}};

static int
_init_globals(void)
{
    if (_channels_init(&_globals.channels) != 0) {
        return -1;
    }
    return 0;
}

static _channels *
_global_channels(void) {
    return &_globals.channels;
}

static PyObject *
interp_create(PyObject *self, PyObject *args)
{
    if (!PyArg_UnpackTuple(args, "create", 0, 0)) {
        return NULL;
    }

    // Create and initialize the new interpreter.
2275 2276 2277
    PyThreadState *save_tstate = PyThreadState_Swap(NULL);
    // XXX Possible GILState issues?
    PyThreadState *tstate = Py_NewInterpreter();
2278 2279 2280 2281 2282 2283 2284 2285
    PyThreadState_Swap(save_tstate);
    if (tstate == NULL) {
        /* Since no new thread state was created, there is no exception to
           propagate; raise a fresh one after swapping in the old thread
           state. */
        PyErr_SetString(PyExc_RuntimeError, "interpreter creation failed");
        return NULL;
    }
2286 2287 2288
    if (_PyInterpreterState_IDInitref(tstate->interp) != 0) {
        goto error;
    };
2289
    return _get_id(tstate->interp);
2290 2291

error:
2292
    // XXX Possible GILState issues?
2293 2294 2295 2296
    save_tstate = PyThreadState_Swap(tstate);
    Py_EndInterpreter(tstate);
    PyThreadState_Swap(save_tstate);
    return NULL;
2297 2298 2299 2300 2301 2302 2303 2304 2305
}

PyDoc_STRVAR(create_doc,
"create() -> ID\n\
\n\
Create a new interpreter and return a unique generated ID.");


static PyObject *
2306
interp_destroy(PyObject *self, PyObject *args, PyObject *kwds)
2307
{
2308
    static char *kwlist[] = {"id", NULL};
2309
    PyObject *id;
2310 2311 2312
    // XXX Use "L" for id?
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                                     "O:destroy", kwlist, &id)) {
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
        return NULL;
    }
    if (!PyLong_Check(id)) {
        PyErr_SetString(PyExc_TypeError, "ID must be an int");
        return NULL;
    }

    // Look up the interpreter.
    PyInterpreterState *interp = _look_up(id);
    if (interp == NULL) {
        return NULL;
    }

    // Ensure we don't try to destroy the current interpreter.
    PyInterpreterState *current = _get_current();
    if (current == NULL) {
        return NULL;
    }
    if (interp == current) {
        PyErr_SetString(PyExc_RuntimeError,
                        "cannot destroy the current interpreter");
        return NULL;
    }

    // Ensure the interpreter isn't running.
    /* XXX We *could* support destroying a running interpreter but
       aren't going to worry about it for now. */
    if (_ensure_not_running(interp) < 0) {
        return NULL;
    }

    // Destroy the interpreter.
    //PyInterpreterState_Delete(interp);
2346 2347 2348
    PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
    // XXX Possible GILState issues?
    PyThreadState *save_tstate = PyThreadState_Swap(tstate);
2349 2350 2351 2352 2353 2354 2355
    Py_EndInterpreter(tstate);
    PyThreadState_Swap(save_tstate);

    Py_RETURN_NONE;
}

PyDoc_STRVAR(destroy_doc,
2356
"destroy(id)\n\
2357 2358 2359 2360 2361 2362 2363 2364
\n\
Destroy the identified interpreter.\n\
\n\
Attempting to destroy the current interpreter results in a RuntimeError.\n\
So does an unrecognized ID.");


static PyObject *
2365
interp_list_all(PyObject *self, PyObject *Py_UNUSED(ignored))
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
{
    PyObject *ids, *id;
    PyInterpreterState *interp;

    ids = PyList_New(0);
    if (ids == NULL) {
        return NULL;
    }

    interp = PyInterpreterState_Head();
    while (interp != NULL) {
        id = _get_id(interp);
        if (id == NULL) {
            Py_DECREF(ids);
            return NULL;
        }
        // insert at front of list
2383 2384 2385
        int res = PyList_Insert(ids, 0, id);
        Py_DECREF(id);
        if (res < 0) {
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
            Py_DECREF(ids);
            return NULL;
        }

        interp = PyInterpreterState_Next(interp);
    }

    return ids;
}

PyDoc_STRVAR(list_all_doc,
"list_all() -> [ID]\n\
\n\
Return a list containing the ID of every existing interpreter.");


static PyObject *
2403
interp_get_current(PyObject *self, PyObject *Py_UNUSED(ignored))
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
{
    PyInterpreterState *interp =_get_current();
    if (interp == NULL) {
        return NULL;
    }
    return _get_id(interp);
}

PyDoc_STRVAR(get_current_doc,
"get_current() -> ID\n\
\n\
Return the ID of current interpreter.");


static PyObject *
2419
interp_get_main(PyObject *self, PyObject *Py_UNUSED(ignored))
2420 2421
{
    // Currently, 0 is always the main interpreter.
2422 2423
    PY_INT64_T id = 0;
    return (PyObject *)newinterpid(&InterpreterIDtype, id, 0);
2424 2425 2426 2427 2428 2429 2430 2431 2432
}

PyDoc_STRVAR(get_main_doc,
"get_main() -> ID\n\
\n\
Return the ID of main interpreter.");


static PyObject *
2433
interp_run_string(PyObject *self, PyObject *args, PyObject *kwds)
2434
{
2435
    static char *kwlist[] = {"id", "script", "shared", NULL};
2436 2437
    PyObject *id, *code;
    PyObject *shared = NULL;
2438 2439 2440
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                                     "OU|O:run_string", kwlist,
                                     &id, &code, &shared)) {
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
        return NULL;
    }
    if (!PyLong_Check(id)) {
        PyErr_SetString(PyExc_TypeError, "first arg (ID) must be an int");
        return NULL;
    }

    // Look up the interpreter.
    PyInterpreterState *interp = _look_up(id);
    if (interp == NULL) {
        return NULL;
    }

    // Extract code.
    Py_ssize_t size;
    const char *codestr = PyUnicode_AsUTF8AndSize(code, &size);
    if (codestr == NULL) {
        return NULL;
    }
    if (strlen(codestr) != (size_t)size) {
        PyErr_SetString(PyExc_ValueError,
                        "source code string cannot contain null bytes");
        return NULL;
    }

    // Run the code in the interpreter.
    if (_run_script_in_interpreter(interp, codestr, shared) != 0) {
        return NULL;
    }
    Py_RETURN_NONE;
}

PyDoc_STRVAR(run_string_doc,
2474
"run_string(id, script, shared)\n\
2475 2476 2477 2478 2479 2480 2481
\n\
Execute the provided string in the identified interpreter.\n\
\n\
See PyRun_SimpleStrings.");


static PyObject *
2482
object_is_shareable(PyObject *self, PyObject *args, PyObject *kwds)
2483
{
2484
    static char *kwlist[] = {"obj", NULL};
2485
    PyObject *obj;
2486 2487
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                                     "O:is_shareable", kwlist, &obj)) {
2488 2489
        return NULL;
    }
2490

2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
    if (_PyObject_CheckCrossInterpreterData(obj) == 0) {
        Py_RETURN_TRUE;
    }
    PyErr_Clear();
    Py_RETURN_FALSE;
}

PyDoc_STRVAR(is_shareable_doc,
"is_shareable(obj) -> bool\n\
\n\
Return True if the object's data may be shared between interpreters and\n\
False otherwise.");


static PyObject *
2506
interp_is_running(PyObject *self, PyObject *args, PyObject *kwds)
2507
{
2508
    static char *kwlist[] = {"id", NULL};
2509
    PyObject *id;
2510 2511
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                                     "O:is_running", kwlist, &id)) {
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
        return NULL;
    }
    if (!PyLong_Check(id)) {
        PyErr_SetString(PyExc_TypeError, "ID must be an int");
        return NULL;
    }

    PyInterpreterState *interp = _look_up(id);
    if (interp == NULL) {
        return NULL;
    }
    int is_running = _is_running(interp);
    if (is_running < 0) {
        return NULL;
    }
    if (is_running) {
        Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
}

PyDoc_STRVAR(is_running_doc,
"is_running(id) -> bool\n\
\n\
Return whether or not the identified interpreter is running.");

static PyObject *
2539
channel_create(PyObject *self, PyObject *Py_UNUSED(ignored))
2540 2541 2542 2543 2544 2545
{
    int64_t cid = _channel_create(&_globals.channels);
    if (cid < 0) {
        return NULL;
    }
    PyObject *id = (PyObject *)newchannelid(&ChannelIDtype, cid, 0,
2546
                                            &_globals.channels, 0, 0);
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
    if (id == NULL) {
        if (_channel_destroy(&_globals.channels, cid) != 0) {
            // XXX issue a warning?
        }
        return NULL;
    }
    assert(((channelid *)id)->channels != NULL);
    return id;
}

PyDoc_STRVAR(channel_create_doc,
2558
"channel_create() -> cid\n\
2559 2560 2561 2562
\n\
Create a new cross-interpreter channel and return a unique generated ID.");

static PyObject *
2563
channel_destroy(PyObject *self, PyObject *args, PyObject *kwds)
2564
{
2565
    static char *kwlist[] = {"cid", NULL};
2566
    PyObject *id;
2567 2568
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                                     "O:channel_destroy", kwlist, &id)) {
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
        return NULL;
    }
    int64_t cid = _coerce_id(id);
    if (cid < 0) {
        return NULL;
    }

    if (_channel_destroy(&_globals.channels, cid) != 0) {
        return NULL;
    }
    Py_RETURN_NONE;
}

PyDoc_STRVAR(channel_destroy_doc,
2583
"channel_destroy(cid)\n\
2584 2585 2586 2587 2588
\n\
Close and finalize the channel.  Afterward attempts to use the channel\n\
will behave as though it never existed.");

static PyObject *
2589
channel_list_all(PyObject *self, PyObject *Py_UNUSED(ignored))
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
{
    int64_t count = 0;
    int64_t *cids = _channels_list_all(&_globals.channels, &count);
    if (cids == NULL) {
        if (count == 0) {
            return PyList_New(0);
        }
        return NULL;
    }
    PyObject *ids = PyList_New((Py_ssize_t)count);
    if (ids == NULL) {
2601
        goto finally;
2602
    }
2603 2604 2605
    int64_t *cur = cids;
    for (int64_t i=0; i < count; cur++, i++) {
        PyObject *id = (PyObject *)newchannelid(&ChannelIDtype, *cur, 0,
2606
                                                &_globals.channels, 0, 0);
2607 2608 2609 2610 2611 2612 2613
        if (id == NULL) {
            Py_DECREF(ids);
            ids = NULL;
            break;
        }
        PyList_SET_ITEM(ids, i, id);
    }
2614 2615 2616

finally:
    PyMem_Free(cids);
2617 2618 2619 2620
    return ids;
}

PyDoc_STRVAR(channel_list_all_doc,
2621
"channel_list_all() -> [cid]\n\
2622 2623 2624 2625
\n\
Return the list of all IDs for active channels.");

static PyObject *
2626
channel_send(PyObject *self, PyObject *args, PyObject *kwds)
2627
{
2628
    static char *kwlist[] = {"cid", "obj", NULL};
2629 2630
    PyObject *id;
    PyObject *obj;
2631 2632
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                                     "OO:channel_send", kwlist, &id, &obj)) {
2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646
        return NULL;
    }
    int64_t cid = _coerce_id(id);
    if (cid < 0) {
        return NULL;
    }

    if (_channel_send(&_globals.channels, cid, obj) != 0) {
        return NULL;
    }
    Py_RETURN_NONE;
}

PyDoc_STRVAR(channel_send_doc,
2647
"channel_send(cid, obj)\n\
2648 2649 2650 2651
\n\
Add the object's data to the channel's queue.");

static PyObject *
2652
channel_recv(PyObject *self, PyObject *args, PyObject *kwds)
2653
{
2654
    static char *kwlist[] = {"cid", NULL};
2655
    PyObject *id;
2656 2657
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                                     "O:channel_recv", kwlist, &id)) {
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
        return NULL;
    }
    int64_t cid = _coerce_id(id);
    if (cid < 0) {
        return NULL;
    }

    return _channel_recv(&_globals.channels, cid);
}

PyDoc_STRVAR(channel_recv_doc,
2669
"channel_recv(cid) -> obj\n\
2670 2671 2672 2673
\n\
Return a new object from the data at the from of the channel's queue.");

static PyObject *
2674
channel_close(PyObject *self, PyObject *args, PyObject *kwds)
2675
{
2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
    static char *kwlist[] = {"cid", "send", "recv", "force", NULL};
    PyObject *id;
    int send = 0;
    int recv = 0;
    int force = 0;
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                                     "O|$ppp:channel_close", kwlist,
                                     &id, &send, &recv, &force)) {
        return NULL;
    }
2686 2687 2688 2689 2690
    int64_t cid = _coerce_id(id);
    if (cid < 0) {
        return NULL;
    }

2691
    if (_channel_close(&_globals.channels, cid, send-recv, force) != 0) {
2692 2693 2694 2695 2696 2697
        return NULL;
    }
    Py_RETURN_NONE;
}

PyDoc_STRVAR(channel_close_doc,
2698 2699 2700
"channel_close(cid, *, send=None, recv=None, force=False)\n\
\n\
Close the channel for all interpreters.\n\
2701
\n\
2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
If the channel is empty then the keyword args are ignored and both\n\
ends are immediately closed.  Otherwise, if 'force' is True then\n\
all queued items are released and both ends are immediately\n\
closed.\n\
\n\
If the channel is not empty *and* 'force' is False then following\n\
happens:\n\
\n\
 * recv is True (regardless of send):\n\
   - raise ChannelNotEmptyError\n\
 * recv is None and send is None:\n\
   - raise ChannelNotEmptyError\n\
 * send is True and recv is not True:\n\
   - fully close the 'send' end\n\
   - close the 'recv' end to interpreters not already receiving\n\
   - fully close it once empty\n\
\n\
Closing an already closed channel results in a ChannelClosedError.\n\
\n\
Once the channel's ID has no more ref counts in any interpreter\n\
the channel will be destroyed.");
2723 2724

static PyObject *
2725
channel_release(PyObject *self, PyObject *args, PyObject *kwds)
2726 2727
{
    // Note that only the current interpreter is affected.
2728
    static char *kwlist[] = {"cid", "send", "recv", "force", NULL};
2729
    PyObject *id;
2730 2731 2732
    int send = 0;
    int recv = 0;
    int force = 0;
2733
    if (!PyArg_ParseTupleAndKeywords(args, kwds,
2734 2735
                                     "O|$ppp:channel_release", kwlist,
                                     &id, &send, &recv, &force)) {
2736
        return NULL;
2737
    }
2738 2739 2740 2741
    int64_t cid = _coerce_id(id);
    if (cid < 0) {
        return NULL;
    }
2742
    if (send == 0 && recv == 0) {
2743 2744 2745
        send = 1;
        recv = 1;
    }
2746 2747 2748 2749

    // XXX Handle force is True.
    // XXX Fix implicit release.

2750 2751 2752 2753 2754 2755
    if (_channel_drop(&_globals.channels, cid, send, recv) != 0) {
        return NULL;
    }
    Py_RETURN_NONE;
}

2756 2757
PyDoc_STRVAR(channel_release_doc,
"channel_release(cid, *, send=None, recv=None, force=True)\n\
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771
\n\
Close the channel for the current interpreter.  'send' and 'recv'\n\
(bool) may be used to indicate the ends to close.  By default both\n\
ends are closed.  Closing an already closed end is a noop.");

static PyObject *
channel__channel_id(PyObject *self, PyObject *args, PyObject *kwds)
{
    return channelid_new(&ChannelIDtype, args, kwds);
}

static PyMethodDef module_functions[] = {
    {"create",                    (PyCFunction)interp_create,
     METH_VARARGS, create_doc},
2772
    {"destroy",                   (PyCFunction)(void(*)(void))interp_destroy,
2773
     METH_VARARGS | METH_KEYWORDS, destroy_doc},
2774
    {"list_all",                  interp_list_all,
2775
     METH_NOARGS, list_all_doc},
2776
    {"get_current",               interp_get_current,
2777
     METH_NOARGS, get_current_doc},
2778
    {"get_main",                  interp_get_main,
2779
     METH_NOARGS, get_main_doc},
2780
    {"is_running",                (PyCFunction)(void(*)(void))interp_is_running,
2781
     METH_VARARGS | METH_KEYWORDS, is_running_doc},
2782
    {"run_string",                (PyCFunction)(void(*)(void))interp_run_string,
2783
     METH_VARARGS | METH_KEYWORDS, run_string_doc},
2784

2785
    {"is_shareable",              (PyCFunction)(void(*)(void))object_is_shareable,
2786
     METH_VARARGS | METH_KEYWORDS, is_shareable_doc},
2787

2788
    {"channel_create",            channel_create,
2789
     METH_NOARGS, channel_create_doc},
2790
    {"channel_destroy",           (PyCFunction)(void(*)(void))channel_destroy,
2791
     METH_VARARGS | METH_KEYWORDS, channel_destroy_doc},
2792
    {"channel_list_all",          channel_list_all,
2793
     METH_NOARGS, channel_list_all_doc},
2794
    {"channel_send",              (PyCFunction)(void(*)(void))channel_send,
2795
     METH_VARARGS | METH_KEYWORDS, channel_send_doc},
2796
    {"channel_recv",              (PyCFunction)(void(*)(void))channel_recv,
2797
     METH_VARARGS | METH_KEYWORDS, channel_recv_doc},
2798
    {"channel_close",             (PyCFunction)(void(*)(void))channel_close,
2799
     METH_VARARGS | METH_KEYWORDS, channel_close_doc},
2800
    {"channel_release",           (PyCFunction)(void(*)(void))channel_release,
2801
     METH_VARARGS | METH_KEYWORDS, channel_release_doc},
2802
    {"_channel_id",               (PyCFunction)(void(*)(void))channel__channel_id,
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
     METH_VARARGS | METH_KEYWORDS, NULL},

    {NULL,                        NULL}           /* sentinel */
};


/* initialization function */

PyDoc_STRVAR(module_doc,
"This module provides primitive operations to manage Python interpreters.\n\
The 'interpreters' module provides a more convenient interface.");

static struct PyModuleDef interpretersmodule = {
    PyModuleDef_HEAD_INIT,
    "_xxsubinterpreters",  /* m_name */
    module_doc,            /* m_doc */
    -1,                    /* m_size */
    module_functions,      /* m_methods */
    NULL,                  /* m_slots */
    NULL,                  /* m_traverse */
    NULL,                  /* m_clear */
    NULL                   /* m_free */
};


PyMODINIT_FUNC
PyInit__xxsubinterpreters(void)
{
    if (_init_globals() != 0) {
        return NULL;
    }

    /* Initialize types */
    ChannelIDtype.tp_base = &PyLong_Type;
    if (PyType_Ready(&ChannelIDtype) != 0) {
        return NULL;
    }
2840 2841 2842 2843
    InterpreterIDtype.tp_base = &PyLong_Type;
    if (PyType_Ready(&InterpreterIDtype) != 0) {
        return NULL;
    }
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864

    /* Create the module */
    PyObject *module = PyModule_Create(&interpretersmodule);
    if (module == NULL) {
        return NULL;
    }

    /* Add exception types */
    PyObject *ns = PyModule_GetDict(module);  // borrowed
    if (interp_exceptions_init(ns) != 0) {
        return NULL;
    }
    if (channel_exceptions_init(ns) != 0) {
        return NULL;
    }

    /* Add other types */
    Py_INCREF(&ChannelIDtype);
    if (PyDict_SetItemString(ns, "ChannelID", (PyObject *)&ChannelIDtype) != 0) {
        return NULL;
    }
2865 2866 2867 2868
    Py_INCREF(&InterpreterIDtype);
    if (PyDict_SetItemString(ns, "InterpreterID", (PyObject *)&InterpreterIDtype) != 0) {
        return NULL;
    }
2869 2870 2871 2872 2873 2874 2875

    if (_PyCrossInterpreterData_Register_Class(&ChannelIDtype, _channelid_shared)) {
        return NULL;
    }

    return module;
}