Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Modules/_asynciomodule.c
Line
Count
Source
1
#ifndef Py_BUILD_CORE_BUILTIN
2
#  define Py_BUILD_CORE_MODULE 1
3
#endif
4
5
#include "Python.h"
6
#include "pycore_freelist.h"      // _Py_FREELIST_POP()
7
#include "pycore_genobject.h"
8
#include "pycore_llist.h"         // struct llist_node
9
#include "pycore_list.h"          // _PyList_AppendTakeRef()
10
#include "pycore_modsupport.h"    // _PyArg_CheckPositional()
11
#include "pycore_moduleobject.h"  // _PyModule_GetState()
12
#include "pycore_object.h"        // _PyObject_SetMaybeWeakref
13
#include "pycore_pylifecycle.h"   // _Py_IsInterpreterFinalizing()
14
#include "pycore_pystate.h"       // _PyThreadState_GET()
15
#include "pycore_runtime_init.h"  // _Py_ID()
16
#include "pycore_tuple.h"         // _PyTuple_FromPair
17
18
#include <stddef.h>               // offsetof()
19
20
21
/*[clinic input]
22
module _asyncio
23
[clinic start generated code]*/
24
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=8fd17862aa989c69]*/
25
26
typedef enum {
27
    STATE_PENDING,
28
    STATE_CANCELLED,
29
    STATE_FINISHED
30
} fut_state;
31
32
#define FutureObj_HEAD(prefix)                                              \
33
    PyObject_HEAD                                                           \
34
    PyObject *prefix##_loop;                                                \
35
    PyObject *prefix##_callback0;                                           \
36
    PyObject *prefix##_context0;                                            \
37
    PyObject *prefix##_callbacks;                                           \
38
    PyObject *prefix##_exception;                                           \
39
    PyObject *prefix##_exception_tb;                                        \
40
    PyObject *prefix##_result;                                              \
41
    PyObject *prefix##_source_tb;                                           \
42
    PyObject *prefix##_cancel_msg;                                          \
43
    PyObject *prefix##_cancelled_exc;                                       \
44
    PyObject *prefix##_awaited_by;                                          \
45
    fut_state prefix##_state;                                               \
46
    /* Used by profilers to make traversing the stack from an external      \
47
       process faster. */                                                   \
48
    char prefix##_is_task;                                                  \
49
    char prefix##_awaited_by_is_set;                                        \
50
    /* These bitfields need to be at the end of the struct                  \
51
       so that these and bitfields from TaskObj are contiguous.             \
52
    */                                                                      \
53
    unsigned prefix##_log_tb: 1;                                            \
54
    unsigned prefix##_blocking: 1;                                          \
55
56
typedef struct {
57
    FutureObj_HEAD(fut)
58
} FutureObj;
59
60
typedef struct TaskObj {
61
    FutureObj_HEAD(task)
62
    unsigned task_must_cancel: 1;
63
    unsigned task_log_destroy_pending: 1;
64
    int task_num_cancels_requested;
65
    PyObject *task_fut_waiter;
66
    PyObject *task_coro;
67
    PyObject *task_name;
68
    PyObject *task_context;
69
    struct llist_node task_node;
70
#ifdef Py_GIL_DISABLED
71
    // unique id of the thread state where the task was registered
72
    uint64_t task_tstate_id;
73
#endif
74
} TaskObj;
75
76
typedef struct {
77
    PyObject_HEAD
78
    TaskObj *sw_task;
79
    PyObject *sw_arg;
80
} TaskStepMethWrapper;
81
82
0
#define Future_CheckExact(state, obj) Py_IS_TYPE(obj, state->FutureType)
83
0
#define Task_CheckExact(state, obj) Py_IS_TYPE(obj, state->TaskType)
84
85
#define Future_Check(state, obj)                        \
86
    (Future_CheckExact(state, obj)                      \
87
     || PyObject_TypeCheck(obj, state->FutureType))
88
89
#define Task_Check(state, obj)                          \
90
0
    (Task_CheckExact(state, obj)                        \
91
0
     || PyObject_TypeCheck(obj, state->TaskType))
92
93
// This macro is optimized to quickly return for native Future *or* Task
94
// objects by inlining fast "exact" checks to be called first.
95
#define TaskOrFuture_Check(state, obj)                  \
96
0
    (Task_CheckExact(state, obj)                        \
97
0
     || Future_CheckExact(state, obj)                   \
98
0
     || PyObject_TypeCheck(obj, state->FutureType)      \
99
0
     || PyObject_TypeCheck(obj, state->TaskType))
100
101
typedef struct _Py_AsyncioModuleDebugOffsets {
102
    struct _asyncio_task_object {
103
        uint64_t size;
104
        uint64_t task_name;
105
        uint64_t task_awaited_by;
106
        uint64_t task_is_task;
107
        uint64_t task_awaited_by_is_set;
108
        uint64_t task_coro;
109
        uint64_t task_node;
110
    } asyncio_task_object;
111
    struct _asyncio_interpreter_state {
112
        uint64_t size;
113
        uint64_t asyncio_tasks_head;
114
    } asyncio_interpreter_state;
115
    struct _asyncio_thread_state {
116
        uint64_t size;
117
        uint64_t asyncio_running_loop;
118
        uint64_t asyncio_running_task;
119
        uint64_t asyncio_tasks_head;
120
    } asyncio_thread_state;
121
} Py_AsyncioModuleDebugOffsets;
122
123
GENERATE_DEBUG_SECTION(AsyncioDebug, Py_AsyncioModuleDebugOffsets _Py_AsyncioDebug)
124
    = {.asyncio_task_object = {
125
           .size = sizeof(TaskObj),
126
           .task_name = offsetof(TaskObj, task_name),
127
           .task_awaited_by = offsetof(TaskObj, task_awaited_by),
128
           .task_is_task = offsetof(TaskObj, task_is_task),
129
           .task_awaited_by_is_set = offsetof(TaskObj, task_awaited_by_is_set),
130
           .task_coro = offsetof(TaskObj, task_coro),
131
           .task_node = offsetof(TaskObj, task_node),
132
       },
133
       .asyncio_interpreter_state = {
134
            .size = sizeof(PyInterpreterState),
135
            .asyncio_tasks_head = offsetof(PyInterpreterState, asyncio_tasks_head),
136
       },
137
       .asyncio_thread_state = {
138
           .size = sizeof(_PyThreadStateImpl),
139
           .asyncio_running_loop = offsetof(_PyThreadStateImpl, asyncio_running_loop),
140
           .asyncio_running_task = offsetof(_PyThreadStateImpl, asyncio_running_task),
141
           .asyncio_tasks_head = offsetof(_PyThreadStateImpl, asyncio_tasks_head),
142
       }};
143
144
/* State of the _asyncio module */
145
typedef struct {
146
    PyTypeObject *FutureIterType;
147
    PyTypeObject *TaskStepMethWrapper_Type;
148
    PyTypeObject *FutureType;
149
    PyTypeObject *TaskType;
150
151
    PyObject *asyncio_mod;
152
    PyObject *context_kwname;
153
154
    /* WeakSet containing scheduled 3rd party tasks which don't
155
       inherit from native asyncio.Task */
156
    PyObject *non_asyncio_tasks;
157
158
    /* Set containing all 3rd party eagerly executing tasks which don't
159
       inherit from native asyncio.Task */
160
    PyObject *non_asyncio_eager_tasks;
161
162
    /* An isinstance type cache for the 'is_coroutine()' function. */
163
    PyObject *iscoroutine_typecache;
164
165
    /* Imports from asyncio.events. */
166
    PyObject *asyncio_get_event_loop;
167
168
    /* Imports from asyncio.base_futures. */
169
    PyObject *asyncio_future_repr_func;
170
171
    /* Imports from asyncio.exceptions. */
172
    PyObject *asyncio_CancelledError;
173
    PyObject *asyncio_InvalidStateError;
174
175
    /* Imports from asyncio.base_tasks. */
176
    PyObject *asyncio_task_get_stack_func;
177
    PyObject *asyncio_task_print_stack_func;
178
    PyObject *asyncio_task_repr_func;
179
180
    /* Imports from asyncio.coroutines. */
181
    PyObject *asyncio_iscoroutine_func;
182
183
    /* Imports from traceback. */
184
    PyObject *traceback_extract_stack;
185
186
    /* Counter for autogenerated Task names */
187
    uint64_t task_name_counter;
188
189
    /* Pointer to the asyncio debug offset to avoid it to be optimized away
190
       by the compiler */
191
    void *debug_offsets;
192
193
} asyncio_state;
194
195
static inline asyncio_state *
196
get_asyncio_state(PyObject *mod)
197
0
{
198
0
    asyncio_state *state = _PyModule_GetState(mod);
199
0
    assert(state != NULL);
200
0
    return state;
201
0
}
202
203
static inline asyncio_state *
204
get_asyncio_state_by_cls(PyTypeObject *cls)
205
0
{
206
0
    asyncio_state *state = (asyncio_state *)_PyType_GetModuleState(cls);
207
0
    assert(state != NULL);
208
0
    return state;
209
0
}
210
211
static struct PyModuleDef _asynciomodule;
212
213
static inline asyncio_state *
214
get_asyncio_state_by_def(PyObject *self)
215
0
{
216
0
    PyTypeObject *tp = Py_TYPE(self);
217
0
    PyObject *mod = PyType_GetModuleByDef(tp, &_asynciomodule);
218
0
    assert(mod != NULL);
219
0
    return get_asyncio_state(mod);
220
0
}
221
222
#include "clinic/_asynciomodule.c.h"
223
224
225
/*[clinic input]
226
class _asyncio.Future "FutureObj *" "&Future_Type"
227
[clinic start generated code]*/
228
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=00d3e4abca711e0f]*/
229
230
231
/* Get FutureIter from Future */
232
static PyObject * future_new_iter(PyObject *);
233
234
static PyObject *
235
task_step_handle_result_impl(asyncio_state *state, TaskObj *task, PyObject *result);
236
static void unregister_task(TaskObj *task);
237
238
static void
239
clear_task_coro(TaskObj *task)
240
0
{
241
0
    Py_CLEAR(task->task_coro);
242
0
}
243
244
245
static void
246
set_task_coro(TaskObj *task, PyObject *coro)
247
0
{
248
0
    assert(coro != NULL);
249
0
    Py_INCREF(coro);
250
0
    Py_XSETREF(task->task_coro, coro);
251
0
}
252
253
254
static int
255
_is_coroutine(asyncio_state *state, PyObject *coro)
256
0
{
257
    /* 'coro' is not a native coroutine, call asyncio.iscoroutine()
258
       to check if it's another coroutine flavour.
259
260
       Do this check after 'future_init()'; in case we need to raise
261
       an error, __del__ needs a properly initialized object.
262
    */
263
0
    PyObject *res = PyObject_CallOneArg(state->asyncio_iscoroutine_func, coro);
264
0
    if (res == NULL) {
265
0
        return -1;
266
0
    }
267
268
0
    int is_res_true = PyObject_IsTrue(res);
269
0
    Py_DECREF(res);
270
0
    if (is_res_true <= 0) {
271
0
        return is_res_true;
272
0
    }
273
274
0
    if (PySet_GET_SIZE(state->iscoroutine_typecache) < 100) {
275
        /* Just in case we don't want to cache more than 100
276
           positive types.  That shouldn't ever happen, unless
277
           someone stressing the system on purpose.
278
        */
279
0
        if (PySet_Add(state->iscoroutine_typecache, (PyObject*) Py_TYPE(coro))) {
280
0
            return -1;
281
0
        }
282
0
    }
283
284
0
    return 1;
285
0
}
286
287
288
static inline int
289
is_coroutine(asyncio_state *state, PyObject *coro)
290
0
{
291
0
    if (PyCoro_CheckExact(coro)) {
292
0
        return 1;
293
0
    }
294
295
    /* Check if `type(coro)` is in the cache.
296
       Caching makes is_coroutine() function almost as fast as
297
       PyCoro_CheckExact() for non-native coroutine-like objects
298
       (like coroutines compiled with Cython).
299
300
       asyncio.iscoroutine() has its own type caching mechanism.
301
       This cache allows us to avoid the cost of even calling
302
       a pure-Python function in 99.9% cases.
303
    */
304
0
    int has_it = PySet_Contains(
305
0
        state->iscoroutine_typecache, (PyObject*) Py_TYPE(coro));
306
0
    if (has_it == 0) {
307
        /* type(coro) is not in iscoroutine_typecache */
308
0
        return _is_coroutine(state, coro);
309
0
    }
310
311
    /* either an error has occurred or
312
       type(coro) is in iscoroutine_typecache
313
    */
314
0
    return has_it;
315
0
}
316
317
318
static PyObject *
319
get_future_loop(asyncio_state *state, PyObject *fut)
320
0
{
321
    /* Implementation of `asyncio.futures._get_loop` */
322
323
0
    PyObject *getloop;
324
325
0
    if (Future_CheckExact(state, fut) || Task_CheckExact(state, fut)) {
326
0
        PyObject *loop = ((FutureObj *)fut)->fut_loop;
327
0
        return Py_NewRef(loop);
328
0
    }
329
330
0
    if (PyObject_GetOptionalAttr(fut, &_Py_ID(get_loop), &getloop) < 0) {
331
0
        return NULL;
332
0
    }
333
0
    if (getloop != NULL) {
334
0
        PyObject *res = PyObject_CallNoArgs(getloop);
335
0
        Py_DECREF(getloop);
336
0
        return res;
337
0
    }
338
339
0
    return PyObject_GetAttr(fut, &_Py_ID(_loop));
340
0
}
341
342
static PyObject *
343
get_event_loop(asyncio_state *state)
344
0
{
345
0
    PyObject *loop;
346
347
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
348
0
    loop = Py_XNewRef(ts->asyncio_running_loop);
349
350
0
    if (loop != NULL) {
351
0
        return loop;
352
0
    }
353
354
0
    return PyObject_CallNoArgs(state->asyncio_get_event_loop);
355
0
}
356
357
358
static int
359
call_soon(asyncio_state *state, PyObject *loop, PyObject *func, PyObject *arg,
360
          PyObject *ctx)
361
0
{
362
0
    PyObject *handle;
363
364
0
    if (ctx == NULL) {
365
0
        PyObject *stack[] = {loop, func, arg};
366
0
        size_t nargsf = 3 | PY_VECTORCALL_ARGUMENTS_OFFSET;
367
0
        handle = PyObject_VectorcallMethod(&_Py_ID(call_soon), stack, nargsf, NULL);
368
0
    }
369
0
    else {
370
        /* All refs in 'stack' are borrowed. */
371
0
        PyObject *stack[4];
372
0
        size_t nargs = 2;
373
0
        stack[0] = loop;
374
0
        stack[1] = func;
375
0
        if (arg != NULL) {
376
0
            stack[2] = arg;
377
0
            nargs++;
378
0
        }
379
0
        stack[nargs] = (PyObject *)ctx;
380
0
        size_t nargsf = nargs | PY_VECTORCALL_ARGUMENTS_OFFSET;
381
0
        handle = PyObject_VectorcallMethod(&_Py_ID(call_soon), stack, nargsf,
382
0
                                           state->context_kwname);
383
0
    }
384
385
0
    if (handle == NULL) {
386
0
        return -1;
387
0
    }
388
0
    Py_DECREF(handle);
389
0
    return 0;
390
0
}
391
392
393
static inline int
394
future_is_alive(FutureObj *fut)
395
0
{
396
0
    return fut->fut_loop != NULL;
397
0
}
398
399
400
static inline int
401
future_ensure_alive(FutureObj *fut)
402
0
{
403
0
    if (!future_is_alive(fut)) {
404
0
        PyErr_SetString(PyExc_RuntimeError,
405
0
                        "Future object is not initialized.");
406
0
        return -1;
407
0
    }
408
0
    return 0;
409
0
}
410
411
412
#define ENSURE_FUTURE_ALIVE(state, fut)                             \
413
0
    do {                                                            \
414
0
        assert(Future_Check(state, fut) || Task_Check(state, fut)); \
415
0
        (void)state;                                                \
416
0
        if (future_ensure_alive((FutureObj*)fut)) {                 \
417
0
            return NULL;                                            \
418
0
        }                                                           \
419
0
    } while(0);
420
421
422
static int
423
future_schedule_callbacks(asyncio_state *state, FutureObj *fut)
424
0
{
425
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
426
427
0
    assert(fut->fut_state != STATE_PENDING);
428
429
0
    if (Task_Check(state, fut)) {
430
        // remove task from linked-list of tasks
431
        // as it is finished now
432
0
        TaskObj *task = (TaskObj *)fut;
433
0
        unregister_task(task);
434
0
    }
435
436
0
    if (fut->fut_callback0 != NULL) {
437
        /* There's a 1st callback */
438
439
        // Beware: An evil call_soon could alter fut_callback0 or fut_context0.
440
        // Since we are anyway clearing them after the call, whether call_soon
441
        // succeeds or not, the idea is to transfer ownership so that external
442
        // code is not able to alter them during the call.
443
0
        PyObject *fut_callback0 = fut->fut_callback0;
444
0
        fut->fut_callback0 = NULL;
445
0
        PyObject *fut_context0 = fut->fut_context0;
446
0
        fut->fut_context0 = NULL;
447
448
0
        int ret = call_soon(state, fut->fut_loop, fut_callback0,
449
0
                            (PyObject *)fut, fut_context0);
450
0
        Py_CLEAR(fut_callback0);
451
0
        Py_CLEAR(fut_context0);
452
0
        if (ret) {
453
            /* If an error occurs in pure-Python implementation,
454
               all callbacks are cleared. */
455
0
            Py_CLEAR(fut->fut_callbacks);
456
0
            return ret;
457
0
        }
458
459
        /* we called the first callback, now try calling
460
           callbacks from the 'fut_callbacks' list. */
461
0
    }
462
463
0
    if (fut->fut_callbacks == NULL) {
464
        /* No more callbacks, return. */
465
0
        return 0;
466
0
    }
467
468
    // Beware: An evil call_soon could change fut->fut_callbacks.
469
    // The idea is to transfer the ownership of the callbacks list
470
    // so that external code is not able to mutate the list during
471
    // the iteration.
472
0
    PyObject *callbacks = fut->fut_callbacks;
473
0
    fut->fut_callbacks = NULL;
474
0
    Py_ssize_t n = PyList_GET_SIZE(callbacks);
475
0
    for (Py_ssize_t i = 0; i < n; i++) {
476
0
        assert(PyList_GET_SIZE(callbacks) == n);
477
0
        PyObject *cb_tup = PyList_GET_ITEM(callbacks, i);
478
0
        PyObject *cb = PyTuple_GET_ITEM(cb_tup, 0);
479
0
        PyObject *ctx = PyTuple_GET_ITEM(cb_tup, 1);
480
481
0
        if (call_soon(state, fut->fut_loop, cb, (PyObject *)fut, ctx)) {
482
0
            Py_DECREF(callbacks);
483
0
            return -1;
484
0
        }
485
0
    }
486
0
    Py_DECREF(callbacks);
487
0
    return 0;
488
0
}
489
490
491
static int
492
future_init(FutureObj *fut, PyObject *loop)
493
0
{
494
0
    if (fut->fut_loop != NULL) {
495
0
        PyErr_Format(PyExc_RuntimeError, "%T object is already initialized", fut);
496
0
        return -1;
497
0
    }
498
499
0
    PyObject *res;
500
0
    int is_true;
501
0
    fut->fut_state = STATE_PENDING;
502
0
    fut->fut_log_tb = 0;
503
0
    fut->fut_blocking = 0;
504
0
    fut->fut_awaited_by_is_set = 0;
505
0
    fut->fut_is_task = 0;
506
507
0
    if (loop == Py_None) {
508
0
        asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
509
0
        loop = get_event_loop(state);
510
0
        if (loop == NULL) {
511
0
            return -1;
512
0
        }
513
0
    }
514
0
    else {
515
0
        Py_INCREF(loop);
516
0
    }
517
0
    fut->fut_loop = loop;
518
519
0
    res = PyObject_CallMethodNoArgs(fut->fut_loop, &_Py_ID(get_debug));
520
0
    if (res == NULL) {
521
0
        return -1;
522
0
    }
523
0
    is_true = PyObject_IsTrue(res);
524
0
    Py_DECREF(res);
525
0
    if (is_true < 0) {
526
0
        return -1;
527
0
    }
528
0
    if (is_true && !_Py_IsInterpreterFinalizing(_PyInterpreterState_GET())) {
529
        /* Only try to capture the traceback if the interpreter is not being
530
           finalized.  The original motivation to add a `Py_IsFinalizing()`
531
           call was to prevent SIGSEGV when a Future is created in a __del__
532
           method, which is called during the interpreter shutdown and the
533
           traceback module is already unloaded.
534
        */
535
0
        asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
536
0
        fut->fut_source_tb = PyObject_CallNoArgs(state->traceback_extract_stack);
537
0
        if (fut->fut_source_tb == NULL) {
538
0
            return -1;
539
0
        }
540
0
    }
541
542
0
    return 0;
543
0
}
544
545
static int
546
future_awaited_by_add(asyncio_state *state, FutureObj *fut, PyObject *thing)
547
0
{
548
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
549
    // We only want to support native asyncio Futures.
550
    // For further insight see the comment in the Python
551
    // implementation of "future_add_to_awaited_by()".
552
0
    assert(TaskOrFuture_Check(state, fut));
553
0
    assert(TaskOrFuture_Check(state, thing));
554
555
    /* Most futures/task are only awaited by one entity, so we want
556
       to avoid always creating a set for `fut_awaited_by`.
557
    */
558
0
    if (fut->fut_awaited_by == NULL) {
559
0
        assert(!fut->fut_awaited_by_is_set);
560
0
        Py_INCREF(thing);
561
0
        fut->fut_awaited_by = thing;
562
0
        return 0;
563
0
    }
564
565
0
    if (fut->fut_awaited_by_is_set) {
566
0
        assert(PySet_CheckExact(fut->fut_awaited_by));
567
0
        return PySet_Add(fut->fut_awaited_by, thing);
568
0
    }
569
570
0
    PyObject *set = PySet_New(NULL);
571
0
    if (set == NULL) {
572
0
        return -1;
573
0
    }
574
0
    if (PySet_Add(set, thing)) {
575
0
        Py_DECREF(set);
576
0
        return -1;
577
0
    }
578
0
    if (PySet_Add(set, fut->fut_awaited_by)) {
579
0
        Py_DECREF(set);
580
0
        return -1;
581
0
    }
582
0
    Py_SETREF(fut->fut_awaited_by, set);
583
0
    fut->fut_awaited_by_is_set = 1;
584
0
    return 0;
585
0
}
586
587
static int
588
future_awaited_by_discard(asyncio_state *state, FutureObj *fut, PyObject *thing)
589
0
{
590
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
591
    // We only want to support native asyncio Futures.
592
    // For further insight see the comment in the Python
593
    // implementation of "future_add_to_awaited_by()".
594
0
    assert(TaskOrFuture_Check(state, fut));
595
0
    assert(TaskOrFuture_Check(state, thing));
596
597
    /* Following the semantics of 'set.discard()' here in not
598
       raising an error if `thing` isn't in the `awaited_by` "set".
599
    */
600
0
    if (fut->fut_awaited_by == NULL) {
601
0
        return 0;
602
0
    }
603
0
    if (fut->fut_awaited_by == thing) {
604
0
        Py_CLEAR(fut->fut_awaited_by);
605
0
        return 0;
606
0
    }
607
0
    if (fut->fut_awaited_by_is_set) {
608
0
        assert(PySet_CheckExact(fut->fut_awaited_by));
609
0
        int err = PySet_Discard(fut->fut_awaited_by, thing);
610
0
        if (err < 0) {
611
0
            return -1;
612
0
        } else {
613
0
            return 0;
614
0
        }
615
0
    }
616
0
    return 0;
617
0
}
618
619
620
static PyObject *
621
future_set_result(asyncio_state *state, FutureObj *fut, PyObject *res)
622
0
{
623
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
624
625
0
    if (future_ensure_alive(fut)) {
626
0
        return NULL;
627
0
    }
628
629
0
    if (fut->fut_state != STATE_PENDING) {
630
0
        PyErr_SetString(state->asyncio_InvalidStateError, "invalid state");
631
0
        return NULL;
632
0
    }
633
634
0
    assert(!fut->fut_result);
635
0
    fut->fut_result = Py_NewRef(res);
636
0
    fut->fut_state = STATE_FINISHED;
637
638
0
    if (future_schedule_callbacks(state, fut) == -1) {
639
0
        return NULL;
640
0
    }
641
0
    Py_RETURN_NONE;
642
0
}
643
644
static PyObject *
645
future_set_exception(asyncio_state *state, FutureObj *fut, PyObject *exc)
646
0
{
647
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
648
649
0
    PyObject *exc_val = NULL;
650
651
0
    if (fut->fut_state != STATE_PENDING) {
652
0
        PyErr_SetString(state->asyncio_InvalidStateError, "invalid state");
653
0
        return NULL;
654
0
    }
655
656
0
    if (PyExceptionClass_Check(exc)) {
657
0
        exc_val = PyObject_CallNoArgs(exc);
658
0
        if (exc_val == NULL) {
659
0
            return NULL;
660
0
        }
661
0
        if (fut->fut_state != STATE_PENDING) {
662
0
            Py_DECREF(exc_val);
663
0
            PyErr_SetString(state->asyncio_InvalidStateError, "invalid state");
664
0
            return NULL;
665
0
        }
666
0
    }
667
0
    else {
668
0
        exc_val = Py_NewRef(exc);
669
0
    }
670
0
    if (!PyExceptionInstance_Check(exc_val)) {
671
0
        Py_DECREF(exc_val);
672
0
        PyErr_SetString(PyExc_TypeError, "invalid exception object");
673
0
        return NULL;
674
0
    }
675
0
    if (PyErr_GivenExceptionMatches(exc_val, PyExc_StopIteration)) {
676
0
        const char *msg = "StopIteration interacts badly with "
677
0
                          "generators and cannot be raised into a "
678
0
                          "Future";
679
0
        PyObject *message = PyUnicode_FromString(msg);
680
0
        if (message == NULL) {
681
0
            Py_DECREF(exc_val);
682
0
            return NULL;
683
0
        }
684
0
        PyObject *err = PyObject_CallOneArg(PyExc_RuntimeError, message);
685
0
        Py_DECREF(message);
686
0
        if (err == NULL) {
687
0
            Py_DECREF(exc_val);
688
0
            return NULL;
689
0
        }
690
0
        assert(PyExceptionInstance_Check(err));
691
692
0
        PyException_SetCause(err, Py_NewRef(exc_val));
693
0
        PyException_SetContext(err, Py_NewRef(exc_val));
694
0
        Py_DECREF(exc_val);
695
0
        exc_val = err;
696
0
    }
697
698
0
    assert(!fut->fut_exception);
699
0
    assert(!fut->fut_exception_tb);
700
0
    fut->fut_exception = exc_val;
701
0
    fut->fut_exception_tb = PyException_GetTraceback(exc_val);
702
0
    fut->fut_state = STATE_FINISHED;
703
704
0
    if (future_schedule_callbacks(state, fut) == -1) {
705
0
        return NULL;
706
0
    }
707
708
0
    fut->fut_log_tb = 1;
709
0
    Py_RETURN_NONE;
710
0
}
711
712
static PyObject *
713
create_cancelled_error(asyncio_state *state, FutureObj *fut)
714
0
{
715
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
716
717
0
    PyObject *exc;
718
0
    if (fut->fut_cancelled_exc != NULL) {
719
        /* transfer ownership */
720
0
        exc = fut->fut_cancelled_exc;
721
0
        fut->fut_cancelled_exc = NULL;
722
0
        return exc;
723
0
    }
724
0
    PyObject *msg = fut->fut_cancel_msg;
725
0
    if (msg == NULL || msg == Py_None) {
726
0
        exc = PyObject_CallNoArgs(state->asyncio_CancelledError);
727
0
    } else {
728
0
        exc = PyObject_CallOneArg(state->asyncio_CancelledError, msg);
729
0
    }
730
0
    return exc;
731
0
}
732
733
static void
734
future_set_cancelled_error(asyncio_state *state, FutureObj *fut)
735
0
{
736
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
737
738
0
    PyObject *exc = create_cancelled_error(state, fut);
739
0
    if (exc == NULL) {
740
0
        return;
741
0
    }
742
0
    PyErr_SetObject(state->asyncio_CancelledError, exc);
743
0
    Py_DECREF(exc);
744
0
}
745
746
static int
747
future_get_result(asyncio_state *state, FutureObj *fut, PyObject **result)
748
0
{
749
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
750
751
0
    if (fut->fut_state == STATE_CANCELLED) {
752
0
        future_set_cancelled_error(state, fut);
753
0
        return -1;
754
0
    }
755
756
0
    if (fut->fut_state != STATE_FINISHED) {
757
0
        PyErr_SetString(state->asyncio_InvalidStateError,
758
0
                        "Result is not set.");
759
0
        return -1;
760
0
    }
761
762
0
    fut->fut_log_tb = 0;
763
0
    if (fut->fut_exception != NULL) {
764
0
        PyObject *tb = fut->fut_exception_tb;
765
0
        if (tb == NULL) {
766
0
            tb = Py_None;
767
0
        }
768
0
        if (PyException_SetTraceback(fut->fut_exception, tb) < 0) {
769
0
            return -1;
770
0
        }
771
0
        *result = Py_NewRef(fut->fut_exception);
772
0
        return 1;
773
0
    }
774
775
0
    *result = Py_NewRef(fut->fut_result);
776
0
    return 0;
777
0
}
778
779
static PyObject *
780
future_add_done_callback(asyncio_state *state, FutureObj *fut, PyObject *arg,
781
                         PyObject *ctx)
782
0
{
783
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
784
785
0
    if (!future_is_alive(fut)) {
786
0
        PyErr_SetString(PyExc_RuntimeError, "uninitialized Future object");
787
0
        return NULL;
788
0
    }
789
790
0
    if (fut->fut_state != STATE_PENDING) {
791
        /* The future is done/cancelled, so schedule the callback
792
           right away. */
793
0
        if (call_soon(state, fut->fut_loop, arg, (PyObject*) fut, ctx)) {
794
0
            return NULL;
795
0
        }
796
0
    }
797
0
    else {
798
        /* The future is pending, add a callback.
799
800
           Callbacks in the future object are stored as follows:
801
802
              callback0 -- a pointer to the first callback
803
              callbacks -- a list of 2nd, 3rd, ... callbacks
804
805
           Invariants:
806
807
            * callbacks != NULL:
808
                There are some callbacks in the list.  Just
809
                add the new callback to it.
810
811
            * callbacks == NULL and callback0 == NULL:
812
                This is the first callback.  Set it to callback0.
813
814
            * callbacks == NULL and callback0 != NULL:
815
                This is a second callback.  Initialize callbacks
816
                with a new list and add the new callback to it.
817
        */
818
819
0
        if (fut->fut_callbacks == NULL && fut->fut_callback0 == NULL) {
820
0
            fut->fut_callback0 = Py_NewRef(arg);
821
0
            fut->fut_context0 = Py_NewRef(ctx);
822
0
        }
823
0
        else {
824
0
            PyObject *tup = _PyTuple_FromPair(arg, (PyObject *)ctx);
825
0
            if (tup == NULL) {
826
0
                return NULL;
827
0
            }
828
829
0
            if (fut->fut_callbacks != NULL) {
830
0
                int err = PyList_Append(fut->fut_callbacks, tup);
831
0
                if (err) {
832
0
                    Py_DECREF(tup);
833
0
                    return NULL;
834
0
                }
835
0
                Py_DECREF(tup);
836
0
            }
837
0
            else {
838
0
                fut->fut_callbacks = PyList_New(1);
839
0
                if (fut->fut_callbacks == NULL) {
840
0
                    Py_DECREF(tup);
841
0
                    return NULL;
842
0
                }
843
844
0
                PyList_SET_ITEM(fut->fut_callbacks, 0, tup);  /* borrow */
845
0
            }
846
0
        }
847
0
    }
848
849
0
    Py_RETURN_NONE;
850
0
}
851
852
static PyObject *
853
future_cancel(asyncio_state *state, FutureObj *fut, PyObject *msg)
854
0
{
855
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
856
857
0
    fut->fut_log_tb = 0;
858
859
0
    if (fut->fut_state != STATE_PENDING) {
860
0
        Py_RETURN_FALSE;
861
0
    }
862
0
    fut->fut_state = STATE_CANCELLED;
863
864
0
    Py_XINCREF(msg);
865
0
    Py_XSETREF(fut->fut_cancel_msg, msg);
866
867
0
    if (future_schedule_callbacks(state, fut) == -1) {
868
0
        return NULL;
869
0
    }
870
871
0
    Py_RETURN_TRUE;
872
0
}
873
874
/*[clinic input]
875
@vectorcall
876
_asyncio.Future.__init__
877
878
    *
879
    loop: object = None
880
881
This class is *almost* compatible with concurrent.futures.Future.
882
883
    Differences:
884
885
    - result() and exception() do not take a timeout argument and
886
      raise an exception when the future isn't done yet.
887
888
    - Callbacks registered with add_done_callback() are always called
889
      via the event loop's call_soon_threadsafe().
890
891
    - This class is not compatible with the wait() and as_completed()
892
      methods in the concurrent.futures package.
893
[clinic start generated code]*/
894
895
static int
896
_asyncio_Future___init___impl(FutureObj *self, PyObject *loop)
897
/*[clinic end generated code: output=9ed75799eaccb5d6 input=28ff6d3b6c3aa828]*/
898
899
0
{
900
0
    return future_init(self, loop);
901
0
}
902
903
static int
904
FutureObj_clear(PyObject *op)
905
0
{
906
0
    FutureObj *fut = (FutureObj*)op;
907
0
    Py_CLEAR(fut->fut_loop);
908
0
    Py_CLEAR(fut->fut_callback0);
909
0
    Py_CLEAR(fut->fut_context0);
910
0
    Py_CLEAR(fut->fut_callbacks);
911
0
    Py_CLEAR(fut->fut_result);
912
0
    Py_CLEAR(fut->fut_exception);
913
0
    Py_CLEAR(fut->fut_exception_tb);
914
0
    Py_CLEAR(fut->fut_source_tb);
915
0
    Py_CLEAR(fut->fut_cancel_msg);
916
0
    Py_CLEAR(fut->fut_cancelled_exc);
917
0
    Py_CLEAR(fut->fut_awaited_by);
918
0
    fut->fut_awaited_by_is_set = 0;
919
0
    PyObject_ClearManagedDict((PyObject *)fut);
920
0
    return 0;
921
0
}
922
923
static int
924
FutureObj_traverse(PyObject *op, visitproc visit, void *arg)
925
0
{
926
0
    FutureObj *fut = (FutureObj*)op;
927
0
    Py_VISIT(Py_TYPE(fut));
928
0
    Py_VISIT(fut->fut_loop);
929
0
    Py_VISIT(fut->fut_callback0);
930
0
    Py_VISIT(fut->fut_context0);
931
0
    Py_VISIT(fut->fut_callbacks);
932
0
    Py_VISIT(fut->fut_result);
933
0
    Py_VISIT(fut->fut_exception);
934
0
    Py_VISIT(fut->fut_exception_tb);
935
0
    Py_VISIT(fut->fut_source_tb);
936
0
    Py_VISIT(fut->fut_cancel_msg);
937
0
    Py_VISIT(fut->fut_cancelled_exc);
938
0
    Py_VISIT(fut->fut_awaited_by);
939
0
    return PyObject_VisitManagedDict((PyObject *)fut, visit, arg);
940
0
}
941
942
/*[clinic input]
943
@critical_section
944
_asyncio.Future.result
945
946
Return the result this future represents.
947
948
If the future has been cancelled, raises CancelledError.  If the
949
future's result isn't yet available, raises InvalidStateError.  If
950
the future is done and has an exception set, this exception is
951
raised.
952
[clinic start generated code]*/
953
954
static PyObject *
955
_asyncio_Future_result_impl(FutureObj *self)
956
/*[clinic end generated code: output=f35f940936a4b1e5 input=ee20e126776cbb04]*/
957
0
{
958
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
959
0
    PyObject *result;
960
961
0
    if (!future_is_alive(self)) {
962
0
        PyErr_SetString(state->asyncio_InvalidStateError,
963
0
                        "Future object is not initialized.");
964
0
        return NULL;
965
0
    }
966
967
0
    int res = future_get_result(state, self, &result);
968
969
0
    if (res == -1) {
970
0
        return NULL;
971
0
    }
972
973
0
    if (res == 0) {
974
0
        return result;
975
0
    }
976
977
0
    assert(res == 1);
978
979
0
    PyErr_SetObject(PyExceptionInstance_Class(result), result);
980
0
    Py_DECREF(result);
981
0
    return NULL;
982
0
}
983
984
/*[clinic input]
985
@critical_section
986
_asyncio.Future.exception
987
988
    cls: defining_class
989
    /
990
991
Return the exception that was set on this future.
992
993
The exception (or None if no exception was set) is returned only if
994
the future is done.  If the future has been cancelled, raises
995
CancelledError.  If the future isn't done yet, raises
996
InvalidStateError.
997
[clinic start generated code]*/
998
999
static PyObject *
1000
_asyncio_Future_exception_impl(FutureObj *self, PyTypeObject *cls)
1001
/*[clinic end generated code: output=ce75576b187c905b input=647d1fd1fc403301]*/
1002
0
{
1003
0
    if (!future_is_alive(self)) {
1004
0
        asyncio_state *state = get_asyncio_state_by_cls(cls);
1005
0
        PyErr_SetString(state->asyncio_InvalidStateError,
1006
0
                        "Future object is not initialized.");
1007
0
        return NULL;
1008
0
    }
1009
1010
0
    if (self->fut_state == STATE_CANCELLED) {
1011
0
        asyncio_state *state = get_asyncio_state_by_cls(cls);
1012
0
        future_set_cancelled_error(state, self);
1013
0
        return NULL;
1014
0
    }
1015
1016
0
    if (self->fut_state != STATE_FINISHED) {
1017
0
        asyncio_state *state = get_asyncio_state_by_cls(cls);
1018
0
        PyErr_SetString(state->asyncio_InvalidStateError,
1019
0
                        "Exception is not set.");
1020
0
        return NULL;
1021
0
    }
1022
1023
0
    if (self->fut_exception != NULL) {
1024
0
        self->fut_log_tb = 0;
1025
0
        return Py_NewRef(self->fut_exception);
1026
0
    }
1027
1028
0
    Py_RETURN_NONE;
1029
0
}
1030
1031
/*[clinic input]
1032
@critical_section
1033
_asyncio.Future.set_result
1034
1035
    cls: defining_class
1036
    result: object
1037
    /
1038
1039
Mark the future done and set its result.
1040
1041
If the future is already done when this method is called, raises
1042
InvalidStateError.
1043
[clinic start generated code]*/
1044
1045
static PyObject *
1046
_asyncio_Future_set_result_impl(FutureObj *self, PyTypeObject *cls,
1047
                                PyObject *result)
1048
/*[clinic end generated code: output=99afbbe78f99c32d input=4069306f03a3b6ee]*/
1049
0
{
1050
0
    asyncio_state *state = get_asyncio_state_by_cls(cls);
1051
0
    ENSURE_FUTURE_ALIVE(state, self)
1052
0
    return future_set_result(state, self, result);
1053
0
}
1054
1055
/*[clinic input]
1056
@critical_section
1057
_asyncio.Future.set_exception
1058
1059
    cls: defining_class
1060
    exception: object
1061
    /
1062
1063
Mark the future done and set an exception.
1064
1065
If the future is already done when this method is called, raises
1066
InvalidStateError.
1067
[clinic start generated code]*/
1068
1069
static PyObject *
1070
_asyncio_Future_set_exception_impl(FutureObj *self, PyTypeObject *cls,
1071
                                   PyObject *exception)
1072
/*[clinic end generated code: output=0a5e8b5a52f058d6 input=b6eab43a389bc966]*/
1073
0
{
1074
0
    asyncio_state *state = get_asyncio_state_by_cls(cls);
1075
0
    ENSURE_FUTURE_ALIVE(state, self)
1076
0
    return future_set_exception(state, self, exception);
1077
0
}
1078
1079
/*[clinic input]
1080
@critical_section
1081
_asyncio.Future.add_done_callback
1082
1083
    cls: defining_class
1084
    fn: object
1085
    /
1086
    *
1087
    context: object = NULL
1088
1089
Add a callback to be run when the future becomes done.
1090
1091
The callback is called with a single argument - the future object.
1092
If the future is already done when this is called, the callback is
1093
scheduled with call_soon.
1094
[clinic start generated code]*/
1095
1096
static PyObject *
1097
_asyncio_Future_add_done_callback_impl(FutureObj *self, PyTypeObject *cls,
1098
                                       PyObject *fn, PyObject *context)
1099
/*[clinic end generated code: output=922e9a4cbd601167 input=f4f6adb074cd3e0f]*/
1100
0
{
1101
0
    asyncio_state *state = get_asyncio_state_by_cls(cls);
1102
0
    if (context == NULL) {
1103
0
        context = PyContext_CopyCurrent();
1104
0
        if (context == NULL) {
1105
0
            return NULL;
1106
0
        }
1107
0
        PyObject *res = future_add_done_callback(state, self, fn, context);
1108
0
        Py_DECREF(context);
1109
0
        return res;
1110
0
    }
1111
0
    return future_add_done_callback(state, self, fn, context);
1112
0
}
1113
1114
/*[clinic input]
1115
@critical_section
1116
_asyncio.Future.remove_done_callback
1117
1118
    cls: defining_class
1119
    fn: object
1120
    /
1121
1122
Remove all instances of a callback from the "call when done" list.
1123
1124
Returns the number of callbacks removed.
1125
[clinic start generated code]*/
1126
1127
static PyObject *
1128
_asyncio_Future_remove_done_callback_impl(FutureObj *self, PyTypeObject *cls,
1129
                                          PyObject *fn)
1130
/*[clinic end generated code: output=2da35ccabfe41b98 input=3afbc9f6a673091b]*/
1131
0
{
1132
0
    PyObject *newlist;
1133
0
    Py_ssize_t len, i, j=0;
1134
0
    Py_ssize_t cleared_callback0 = 0;
1135
1136
0
    asyncio_state *state = get_asyncio_state_by_cls(cls);
1137
0
    ENSURE_FUTURE_ALIVE(state, self)
1138
1139
0
    if (self->fut_callback0 != NULL) {
1140
        // Beware: An evil PyObject_RichCompareBool could free fut_callback0
1141
        // before a recursive call is made with that same arg. For details, see
1142
        // https://github.com/python/cpython/pull/125967#discussion_r1816593340.
1143
0
        PyObject *fut_callback0 = Py_NewRef(self->fut_callback0);
1144
0
        int cmp = PyObject_RichCompareBool(fut_callback0, fn, Py_EQ);
1145
0
        Py_DECREF(fut_callback0);
1146
0
        if (cmp == -1) {
1147
0
            return NULL;
1148
0
        }
1149
0
        if (cmp == 1) {
1150
            /* callback0 == fn */
1151
0
            Py_CLEAR(self->fut_callback0);
1152
0
            Py_CLEAR(self->fut_context0);
1153
0
            cleared_callback0 = 1;
1154
0
        }
1155
0
    }
1156
1157
0
    if (self->fut_callbacks == NULL) {
1158
0
        return PyLong_FromSsize_t(cleared_callback0);
1159
0
    }
1160
1161
0
    len = PyList_GET_SIZE(self->fut_callbacks);
1162
0
    if (len == 0) {
1163
0
        Py_CLEAR(self->fut_callbacks);
1164
0
        return PyLong_FromSsize_t(cleared_callback0);
1165
0
    }
1166
1167
0
    if (len == 1) {
1168
0
        PyObject *cb_tup = PyList_GET_ITEM(self->fut_callbacks, 0);
1169
0
        Py_INCREF(cb_tup);
1170
0
        int cmp = PyObject_RichCompareBool(
1171
0
            PyTuple_GET_ITEM(cb_tup, 0), fn, Py_EQ);
1172
0
        Py_DECREF(cb_tup);
1173
0
        if (cmp == -1) {
1174
0
            return NULL;
1175
0
        }
1176
0
        if (cmp == 1) {
1177
            /* callbacks[0] == fn */
1178
0
            Py_CLEAR(self->fut_callbacks);
1179
0
            return PyLong_FromSsize_t(1 + cleared_callback0);
1180
0
        }
1181
        /* callbacks[0] != fn and len(callbacks) == 1 */
1182
0
        return PyLong_FromSsize_t(cleared_callback0);
1183
0
    }
1184
1185
0
    newlist = PyList_New(len);
1186
0
    if (newlist == NULL) {
1187
0
        return NULL;
1188
0
    }
1189
1190
    // Beware: PyObject_RichCompareBool below may change fut_callbacks.
1191
    // See GH-97592.
1192
0
    for (i = 0;
1193
0
         self->fut_callbacks != NULL && i < PyList_GET_SIZE(self->fut_callbacks);
1194
0
         i++) {
1195
0
        int ret;
1196
0
        PyObject *item = PyList_GET_ITEM(self->fut_callbacks, i);
1197
0
        Py_INCREF(item);
1198
0
        ret = PyObject_RichCompareBool(PyTuple_GET_ITEM(item, 0), fn, Py_EQ);
1199
0
        if (ret == 0) {
1200
0
            if (j < len) {
1201
0
                PyList_SET_ITEM(newlist, j, item);
1202
0
                j++;
1203
0
                continue;
1204
0
            }
1205
0
            ret = PyList_Append(newlist, item);
1206
0
        }
1207
0
        Py_DECREF(item);
1208
0
        if (ret < 0) {
1209
0
            goto fail;
1210
0
        }
1211
0
    }
1212
1213
    // Note: fut_callbacks may have been cleared.
1214
0
    if (j == 0 || self->fut_callbacks == NULL) {
1215
0
        Py_CLEAR(self->fut_callbacks);
1216
0
        Py_DECREF(newlist);
1217
0
        return PyLong_FromSsize_t(len + cleared_callback0);
1218
0
    }
1219
1220
0
    if (j < len) {
1221
0
        Py_SET_SIZE(newlist, j);
1222
0
    }
1223
0
    j = PyList_GET_SIZE(newlist);
1224
0
    len = PyList_GET_SIZE(self->fut_callbacks);
1225
0
    if (j != len) {
1226
0
        if (PyList_SetSlice(self->fut_callbacks, 0, len, newlist) < 0) {
1227
0
            goto fail;
1228
0
        }
1229
0
    }
1230
0
    Py_DECREF(newlist);
1231
0
    return PyLong_FromSsize_t(len - j + cleared_callback0);
1232
1233
0
fail:
1234
0
    Py_DECREF(newlist);
1235
0
    return NULL;
1236
0
}
1237
1238
/*[clinic input]
1239
@critical_section
1240
_asyncio.Future.cancel
1241
1242
    cls: defining_class
1243
    /
1244
    msg: object = None
1245
1246
Cancel the future and schedule callbacks.
1247
1248
If the future is already done or cancelled, return False.
1249
Otherwise, change the future's state to cancelled, schedule the
1250
callbacks and return True.
1251
[clinic start generated code]*/
1252
1253
static PyObject *
1254
_asyncio_Future_cancel_impl(FutureObj *self, PyTypeObject *cls,
1255
                            PyObject *msg)
1256
/*[clinic end generated code: output=074956f35904b034 input=0c9157547a964c4c]*/
1257
0
{
1258
0
    asyncio_state *state = get_asyncio_state_by_cls(cls);
1259
0
    ENSURE_FUTURE_ALIVE(state, self)
1260
0
    return future_cancel(state, self, msg);
1261
0
}
1262
1263
/*[clinic input]
1264
@critical_section
1265
_asyncio.Future.cancelled
1266
1267
Return True if the future was cancelled.
1268
[clinic start generated code]*/
1269
1270
static PyObject *
1271
_asyncio_Future_cancelled_impl(FutureObj *self)
1272
/*[clinic end generated code: output=145197ced586357d input=9b8644819a675416]*/
1273
0
{
1274
0
    if (future_is_alive(self) && self->fut_state == STATE_CANCELLED) {
1275
0
        Py_RETURN_TRUE;
1276
0
    }
1277
0
    else {
1278
0
        Py_RETURN_FALSE;
1279
0
    }
1280
0
}
1281
1282
/*[clinic input]
1283
@critical_section
1284
_asyncio.Future.done
1285
1286
Return True if the future is done.
1287
1288
Done means either that a result / exception are available, or that
1289
the future was cancelled.
1290
[clinic start generated code]*/
1291
1292
static PyObject *
1293
_asyncio_Future_done_impl(FutureObj *self)
1294
/*[clinic end generated code: output=244c5ac351145096 input=acf2c2347f3c01d8]*/
1295
0
{
1296
0
    if (!future_is_alive(self) || self->fut_state == STATE_PENDING) {
1297
0
        Py_RETURN_FALSE;
1298
0
    }
1299
0
    else {
1300
0
        Py_RETURN_TRUE;
1301
0
    }
1302
0
}
1303
1304
/*[clinic input]
1305
@critical_section
1306
_asyncio.Future.get_loop
1307
1308
    cls: defining_class
1309
    /
1310
1311
Return the event loop the Future is bound to.
1312
[clinic start generated code]*/
1313
1314
static PyObject *
1315
_asyncio_Future_get_loop_impl(FutureObj *self, PyTypeObject *cls)
1316
/*[clinic end generated code: output=f50ea6c374d9ee97 input=f3ce629bfd9f45c1]*/
1317
0
{
1318
0
    asyncio_state *state = get_asyncio_state_by_cls(cls);
1319
0
    ENSURE_FUTURE_ALIVE(state, self)
1320
0
    return Py_NewRef(self->fut_loop);
1321
0
}
1322
1323
/*[clinic input]
1324
@critical_section
1325
@getter
1326
_asyncio.Future._asyncio_awaited_by
1327
[clinic start generated code]*/
1328
1329
static PyObject *
1330
_asyncio_Future__asyncio_awaited_by_get_impl(FutureObj *self)
1331
/*[clinic end generated code: output=932af76d385d2e2a input=64c1783df2d44d2b]*/
1332
0
{
1333
    /* Implementation of a Python getter. */
1334
0
    if (self->fut_awaited_by == NULL) {
1335
0
        Py_RETURN_NONE;
1336
0
    }
1337
0
    if (self->fut_awaited_by_is_set) {
1338
        /* Already a set, just wrap it into a frozen set and return. */
1339
0
        assert(PySet_CheckExact(self->fut_awaited_by));
1340
0
        return PyFrozenSet_New(self->fut_awaited_by);
1341
0
    }
1342
1343
0
    PyObject *set = PyFrozenSet_New(NULL);
1344
0
    if (set == NULL) {
1345
0
        return NULL;
1346
0
    }
1347
0
    if (PySet_Add(set, self->fut_awaited_by)) {
1348
0
        Py_DECREF(set);
1349
0
        return NULL;
1350
0
    }
1351
0
    return set;
1352
0
}
1353
1354
1355
/*[clinic input]
1356
@critical_section
1357
@getter
1358
_asyncio.Future._asyncio_future_blocking -> bool
1359
[clinic start generated code]*/
1360
1361
static int
1362
_asyncio_Future__asyncio_future_blocking_get_impl(FutureObj *self)
1363
/*[clinic end generated code: output=32944de3df031979 input=2a51a0cf31a96826]*/
1364
0
{
1365
0
    return future_is_alive(self) && self->fut_blocking;
1366
0
}
1367
1368
/*[clinic input]
1369
@critical_section
1370
@setter
1371
_asyncio.Future._asyncio_future_blocking
1372
    value: bool
1373
[clinic start generated code]*/
1374
1375
static int
1376
_asyncio_Future__asyncio_future_blocking_set_impl(FutureObj *self, int value)
1377
/*[clinic end generated code: output=be2d5cb1cad6dd30 input=81780cb7b89f28e1]*/
1378
0
{
1379
0
    if (future_ensure_alive(self)) {
1380
0
        return -1;
1381
0
    }
1382
0
    self->fut_blocking = value;
1383
0
    return 0;
1384
0
}
1385
1386
/*[clinic input]
1387
@critical_section
1388
@getter
1389
_asyncio.Future._log_traceback -> bool
1390
[clinic start generated code]*/
1391
1392
static int
1393
_asyncio_Future__log_traceback_get_impl(FutureObj *self)
1394
/*[clinic end generated code: output=ba1356634182ac25 input=50f4db8eca9d1fb4]*/
1395
0
{
1396
0
    if (future_ensure_alive(self)) {
1397
0
        return -1;
1398
0
    }
1399
0
    return self->fut_log_tb;
1400
0
}
1401
1402
/*[clinic input]
1403
@critical_section
1404
@setter
1405
_asyncio.Future._log_traceback
1406
    value: bool
1407
[clinic start generated code]*/
1408
1409
static int
1410
_asyncio_Future__log_traceback_set_impl(FutureObj *self, int value)
1411
/*[clinic end generated code: output=ad84ae67ef80e3ad input=30c0f841c945c73f]*/
1412
0
{
1413
0
    if (value) {
1414
0
        PyErr_SetString(PyExc_ValueError,
1415
0
                        "_log_traceback can only be set to False");
1416
0
        return -1;
1417
0
    }
1418
0
    self->fut_log_tb = value;
1419
0
    return 0;
1420
0
}
1421
/*[clinic input]
1422
@critical_section
1423
@getter
1424
_asyncio.Future._loop
1425
[clinic start generated code]*/
1426
1427
static PyObject *
1428
_asyncio_Future__loop_get_impl(FutureObj *self)
1429
/*[clinic end generated code: output=5ba31563eecfeedf input=0337130bc5781670]*/
1430
0
{
1431
0
    if (!future_is_alive(self)) {
1432
0
        Py_RETURN_NONE;
1433
0
    }
1434
0
    return Py_NewRef(self->fut_loop);
1435
0
}
1436
1437
/*[clinic input]
1438
@critical_section
1439
@getter
1440
_asyncio.Future._callbacks
1441
[clinic start generated code]*/
1442
1443
static PyObject *
1444
_asyncio_Future__callbacks_get_impl(FutureObj *self)
1445
/*[clinic end generated code: output=b40d360505fcc583 input=7a466649530c01bb]*/
1446
0
{
1447
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
1448
0
    ENSURE_FUTURE_ALIVE(state, self)
1449
1450
0
    Py_ssize_t len = 0;
1451
0
    if (self->fut_callback0 != NULL) {
1452
0
        len++;
1453
0
    }
1454
0
    if (self->fut_callbacks != NULL) {
1455
0
        len += PyList_GET_SIZE(self->fut_callbacks);
1456
0
    }
1457
1458
0
    if (len == 0) {
1459
0
        Py_RETURN_NONE;
1460
0
    }
1461
1462
0
    PyObject *callbacks = PyList_New(len);
1463
0
    if (callbacks == NULL) {
1464
0
        return NULL;
1465
0
    }
1466
1467
0
    Py_ssize_t i = 0;
1468
0
    if (self->fut_callback0 != NULL) {
1469
0
        assert(self->fut_context0 != NULL);
1470
0
        PyObject *tup0 = _PyTuple_FromPair(self->fut_callback0, self->fut_context0);
1471
0
        if (tup0 == NULL) {
1472
0
            Py_DECREF(callbacks);
1473
0
            return NULL;
1474
0
        }
1475
0
        PyList_SET_ITEM(callbacks, i, tup0);
1476
0
        i++;
1477
0
    }
1478
1479
0
    if (self->fut_callbacks != NULL) {
1480
0
        for (Py_ssize_t j = 0; j < PyList_GET_SIZE(self->fut_callbacks); j++) {
1481
0
            PyObject *cb = PyList_GET_ITEM(self->fut_callbacks, j);
1482
0
            Py_INCREF(cb);
1483
0
            PyList_SET_ITEM(callbacks, i, cb);
1484
0
            i++;
1485
0
        }
1486
0
    }
1487
1488
0
    return callbacks;
1489
0
}
1490
1491
/*[clinic input]
1492
@critical_section
1493
@getter
1494
_asyncio.Future._result
1495
[clinic start generated code]*/
1496
1497
static PyObject *
1498
_asyncio_Future__result_get_impl(FutureObj *self)
1499
/*[clinic end generated code: output=6877e8ce97333873 input=624f8e28e67f2636]*/
1500
1501
0
{
1502
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
1503
0
    ENSURE_FUTURE_ALIVE(state, self)
1504
0
    if (self->fut_result == NULL) {
1505
0
        Py_RETURN_NONE;
1506
0
    }
1507
0
    return Py_NewRef(self->fut_result);
1508
0
}
1509
1510
/*[clinic input]
1511
@critical_section
1512
@getter
1513
_asyncio.Future._exception
1514
[clinic start generated code]*/
1515
1516
static PyObject *
1517
_asyncio_Future__exception_get_impl(FutureObj *self)
1518
/*[clinic end generated code: output=32f2c93b9e021a9b input=1828a1fcac929710]*/
1519
0
{
1520
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
1521
0
    ENSURE_FUTURE_ALIVE(state, self)
1522
0
    if (self->fut_exception == NULL) {
1523
0
        Py_RETURN_NONE;
1524
0
    }
1525
0
    return Py_NewRef(self->fut_exception);
1526
0
}
1527
1528
/*[clinic input]
1529
@critical_section
1530
@getter
1531
_asyncio.Future._source_traceback
1532
[clinic start generated code]*/
1533
1534
static PyObject *
1535
_asyncio_Future__source_traceback_get_impl(FutureObj *self)
1536
/*[clinic end generated code: output=d4f12b09af22f61b input=3c831fbde5da90d0]*/
1537
0
{
1538
0
    if (!future_is_alive(self) || self->fut_source_tb == NULL) {
1539
0
        Py_RETURN_NONE;
1540
0
    }
1541
0
    return Py_NewRef(self->fut_source_tb);
1542
0
}
1543
1544
/*[clinic input]
1545
@critical_section
1546
@getter
1547
_asyncio.Future._cancel_message
1548
[clinic start generated code]*/
1549
1550
static PyObject *
1551
_asyncio_Future__cancel_message_get_impl(FutureObj *self)
1552
/*[clinic end generated code: output=52ef6444f92cedac input=54c12c67082e4eea]*/
1553
0
{
1554
0
    if (self->fut_cancel_msg == NULL) {
1555
0
        Py_RETURN_NONE;
1556
0
    }
1557
0
    return Py_NewRef(self->fut_cancel_msg);
1558
0
}
1559
1560
/*[clinic input]
1561
@critical_section
1562
@setter
1563
_asyncio.Future._cancel_message
1564
[clinic start generated code]*/
1565
1566
static int
1567
_asyncio_Future__cancel_message_set_impl(FutureObj *self, PyObject *value)
1568
/*[clinic end generated code: output=0854b2f77bff2209 input=f461d17f2d891fad]*/
1569
0
{
1570
0
    Py_INCREF(value);
1571
0
    Py_XSETREF(self->fut_cancel_msg, value);
1572
0
    return 0;
1573
0
}
1574
1575
/*[clinic input]
1576
@critical_section
1577
@getter
1578
_asyncio.Future._state
1579
[clinic start generated code]*/
1580
1581
static PyObject *
1582
_asyncio_Future__state_get_impl(FutureObj *self)
1583
/*[clinic end generated code: output=622f560a3fa69c63 input=7c5ad023a93423ff]*/
1584
0
{
1585
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
1586
0
    PyObject *ret = NULL;
1587
1588
0
    ENSURE_FUTURE_ALIVE(state, self)
1589
1590
0
    switch (self->fut_state) {
1591
0
    case STATE_PENDING:
1592
0
        ret = &_Py_ID(PENDING);
1593
0
        break;
1594
0
    case STATE_CANCELLED:
1595
0
        ret = &_Py_ID(CANCELLED);
1596
0
        break;
1597
0
    case STATE_FINISHED:
1598
0
        ret = &_Py_ID(FINISHED);
1599
0
        break;
1600
0
    default:
1601
0
        assert (0);
1602
0
    }
1603
0
    assert(_Py_IsImmortal(ret));
1604
0
    return ret;
1605
0
}
1606
1607
static PyObject *
1608
FutureObj_repr(PyObject *op)
1609
0
{
1610
0
    FutureObj *fut = (FutureObj*)op;
1611
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
1612
0
    ENSURE_FUTURE_ALIVE(state, fut)
1613
0
    return PyObject_CallOneArg(state->asyncio_future_repr_func, (PyObject *)fut);
1614
0
}
1615
1616
/*[clinic input]
1617
@critical_section
1618
_asyncio.Future._make_cancelled_error
1619
1620
Create the CancelledError to raise if the Future is cancelled.
1621
1622
This should only be called once when handling a cancellation since
1623
it erases the context exception value.
1624
[clinic start generated code]*/
1625
1626
static PyObject *
1627
_asyncio_Future__make_cancelled_error_impl(FutureObj *self)
1628
/*[clinic end generated code: output=a5df276f6c1213de input=ccb90df8c3c18bcd]*/
1629
0
{
1630
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
1631
0
    return create_cancelled_error(state, self);
1632
0
}
1633
1634
static void
1635
FutureObj_finalize(PyObject *op)
1636
0
{
1637
0
    FutureObj *fut = (FutureObj*)op;
1638
0
    PyObject *context;
1639
0
    PyObject *message = NULL;
1640
0
    PyObject *func;
1641
1642
0
    if (!fut->fut_log_tb) {
1643
0
        return;
1644
0
    }
1645
0
    assert(fut->fut_exception != NULL);
1646
0
    fut->fut_log_tb = 0;
1647
1648
    /* Save the current exception, if any. */
1649
0
    PyObject *exc = PyErr_GetRaisedException();
1650
1651
0
    context = PyDict_New();
1652
0
    if (context == NULL) {
1653
0
        goto finally;
1654
0
    }
1655
1656
0
    message = PyUnicode_FromFormat(
1657
0
        "%s exception was never retrieved", _PyType_Name(Py_TYPE(fut)));
1658
0
    if (message == NULL) {
1659
0
        goto finally;
1660
0
    }
1661
1662
0
    if (PyDict_SetItem(context, &_Py_ID(message), message) < 0 ||
1663
0
        PyDict_SetItem(context, &_Py_ID(exception), fut->fut_exception) < 0 ||
1664
0
        PyDict_SetItem(context, &_Py_ID(future), (PyObject*)fut) < 0) {
1665
0
        goto finally;
1666
0
    }
1667
0
    if (fut->fut_source_tb != NULL) {
1668
0
        if (PyDict_SetItem(context, &_Py_ID(source_traceback),
1669
0
                              fut->fut_source_tb) < 0) {
1670
0
            goto finally;
1671
0
        }
1672
0
    }
1673
1674
0
    func = PyObject_GetAttr(fut->fut_loop, &_Py_ID(call_exception_handler));
1675
0
    if (func != NULL) {
1676
0
        PyObject *res = PyObject_CallOneArg(func, context);
1677
0
        if (res == NULL) {
1678
0
            PyErr_FormatUnraisable("Exception ignored while calling asyncio "
1679
0
                                   "function %R", func);
1680
0
        }
1681
0
        else {
1682
0
            Py_DECREF(res);
1683
0
        }
1684
0
        Py_DECREF(func);
1685
0
    }
1686
1687
0
finally:
1688
0
    Py_XDECREF(context);
1689
0
    Py_XDECREF(message);
1690
1691
    /* Restore the saved exception. */
1692
0
    PyErr_SetRaisedException(exc);
1693
0
}
1694
1695
static PyMethodDef FutureType_methods[] = {
1696
    _ASYNCIO_FUTURE_RESULT_METHODDEF
1697
    _ASYNCIO_FUTURE_EXCEPTION_METHODDEF
1698
    _ASYNCIO_FUTURE_SET_RESULT_METHODDEF
1699
    _ASYNCIO_FUTURE_SET_EXCEPTION_METHODDEF
1700
    _ASYNCIO_FUTURE_ADD_DONE_CALLBACK_METHODDEF
1701
    _ASYNCIO_FUTURE_REMOVE_DONE_CALLBACK_METHODDEF
1702
    _ASYNCIO_FUTURE_CANCEL_METHODDEF
1703
    _ASYNCIO_FUTURE_CANCELLED_METHODDEF
1704
    _ASYNCIO_FUTURE_DONE_METHODDEF
1705
    _ASYNCIO_FUTURE_GET_LOOP_METHODDEF
1706
    _ASYNCIO_FUTURE__MAKE_CANCELLED_ERROR_METHODDEF
1707
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
1708
    PyDoc_STR("Futures are generic over the type of their results")},
1709
    {NULL, NULL}        /* Sentinel */
1710
};
1711
1712
static PyGetSetDef FutureType_getsetlist[] = {
1713
    _ASYNCIO_FUTURE__STATE_GETSETDEF
1714
    _ASYNCIO_FUTURE__ASYNCIO_FUTURE_BLOCKING_GETSETDEF
1715
    _ASYNCIO_FUTURE__LOOP_GETSETDEF
1716
    _ASYNCIO_FUTURE__CALLBACKS_GETSETDEF
1717
    _ASYNCIO_FUTURE__RESULT_GETSETDEF
1718
    _ASYNCIO_FUTURE__EXCEPTION_GETSETDEF
1719
    _ASYNCIO_FUTURE__LOG_TRACEBACK_GETSETDEF
1720
    _ASYNCIO_FUTURE__SOURCE_TRACEBACK_GETSETDEF
1721
    _ASYNCIO_FUTURE__CANCEL_MESSAGE_GETSETDEF
1722
    _ASYNCIO_FUTURE__ASYNCIO_AWAITED_BY_GETSETDEF
1723
    {NULL} /* Sentinel */
1724
};
1725
1726
static void FutureObj_dealloc(PyObject *self);
1727
1728
static PyType_Slot Future_slots[] = {
1729
    {Py_tp_dealloc, FutureObj_dealloc},
1730
    {Py_tp_repr, FutureObj_repr},
1731
    {Py_tp_doc, (void *)_asyncio_Future___init____doc__},
1732
    {Py_tp_traverse, FutureObj_traverse},
1733
    {Py_tp_clear, FutureObj_clear},
1734
    {Py_tp_iter, future_new_iter},
1735
    {Py_tp_methods, FutureType_methods},
1736
    {Py_tp_getset, FutureType_getsetlist},
1737
    {Py_tp_init, _asyncio_Future___init__},
1738
    {Py_tp_vectorcall, _asyncio_Future_vectorcall},
1739
    {Py_tp_new, PyType_GenericNew},
1740
    {Py_tp_finalize, FutureObj_finalize},
1741
1742
    // async slots
1743
    {Py_am_await, future_new_iter},
1744
    {0, NULL},
1745
};
1746
1747
static PyType_Spec Future_spec = {
1748
    .name = "_asyncio.Future",
1749
    .basicsize = sizeof(FutureObj),
1750
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE |
1751
              Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_MANAGED_DICT |
1752
              Py_TPFLAGS_MANAGED_WEAKREF),
1753
    .slots = Future_slots,
1754
};
1755
1756
static void
1757
FutureObj_dealloc(PyObject *self)
1758
0
{
1759
0
    if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1760
        // resurrected.
1761
0
        return;
1762
0
    }
1763
1764
0
    PyTypeObject *tp = Py_TYPE(self);
1765
0
    PyObject_GC_UnTrack(self);
1766
1767
0
    PyObject_ClearWeakRefs(self);
1768
1769
0
    (void)FutureObj_clear(self);
1770
0
    tp->tp_free(self);
1771
0
    Py_DECREF(tp);
1772
0
}
1773
1774
1775
/*********************** Future Iterator **************************/
1776
1777
typedef struct futureiterobject {
1778
    PyObject_HEAD
1779
    FutureObj *future;
1780
} futureiterobject;
1781
1782
1783
static void
1784
FutureIter_dealloc(PyObject *it)
1785
0
{
1786
0
    PyTypeObject *tp = Py_TYPE(it);
1787
1788
0
    assert(_PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE));
1789
1790
0
    PyObject_GC_UnTrack(it);
1791
0
    tp->tp_clear(it);
1792
1793
0
    if (!_Py_FREELIST_PUSH(futureiters, it, Py_futureiters_MAXFREELIST)) {
1794
0
        PyObject_GC_Del(it);
1795
0
        Py_DECREF(tp);
1796
0
    }
1797
0
}
1798
1799
static PySendResult
1800
FutureIter_am_send_lock_held(FutureObj *fut, PyObject **result)
1801
0
{
1802
0
    PyObject *res;
1803
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(fut);
1804
1805
0
    *result = NULL;
1806
1807
0
    if (fut->fut_state == STATE_PENDING) {
1808
0
        if (!fut->fut_blocking) {
1809
0
            fut->fut_blocking = 1;
1810
0
            *result = Py_NewRef(fut);
1811
0
            return PYGEN_NEXT;
1812
0
        }
1813
0
        PyErr_SetString(PyExc_RuntimeError,
1814
0
                        "await wasn't used with future");
1815
0
        return PYGEN_ERROR;
1816
0
    }
1817
1818
0
    res = _asyncio_Future_result_impl(fut);
1819
0
    if (res != NULL) {
1820
0
        *result = res;
1821
0
        return PYGEN_RETURN;
1822
0
    }
1823
1824
0
    return PYGEN_ERROR;
1825
0
}
1826
1827
static PySendResult
1828
FutureIter_am_send(PyObject *op,
1829
                   PyObject *Py_UNUSED(arg),
1830
                   PyObject **result)
1831
0
{
1832
0
    futureiterobject *it = (futureiterobject*)op;
1833
1834
0
    FutureObj *fut;
1835
0
    Py_BEGIN_CRITICAL_SECTION(op);
1836
0
    fut = (FutureObj*)Py_XNewRef(it->future);
1837
0
    Py_END_CRITICAL_SECTION();
1838
1839
0
    if (fut == NULL) {
1840
0
        PyErr_SetNone(PyExc_StopIteration);
1841
0
        *result = NULL;
1842
0
        return PYGEN_ERROR;
1843
0
    }
1844
1845
    /* arg is unused, see the comment on FutureIter_send for clarification */
1846
0
    PySendResult res;
1847
0
    Py_BEGIN_CRITICAL_SECTION(fut);
1848
0
    res = FutureIter_am_send_lock_held(fut, result);
1849
0
    Py_END_CRITICAL_SECTION();
1850
0
    Py_DECREF(fut);
1851
0
    return res;
1852
0
}
1853
1854
1855
static PyObject *
1856
FutureIter_iternext(PyObject *it)
1857
0
{
1858
0
    PyObject *result;
1859
0
    switch (FutureIter_am_send(it, Py_None, &result)) {
1860
0
        case PYGEN_RETURN:
1861
0
            (void)_PyGen_SetStopIterationValue(result);
1862
0
            Py_DECREF(result);
1863
0
            return NULL;
1864
0
        case PYGEN_NEXT:
1865
0
            return result;
1866
0
        case PYGEN_ERROR:
1867
0
            return NULL;
1868
0
        default:
1869
0
            Py_UNREACHABLE();
1870
0
    }
1871
0
}
1872
1873
static PyObject *
1874
FutureIter_send(PyObject *self, PyObject *unused)
1875
0
{
1876
    /* Future.__iter__ doesn't care about values that are pushed to the
1877
     * generator, it just returns self.result().
1878
     */
1879
0
    return FutureIter_iternext(self);
1880
0
}
1881
1882
static PyObject *
1883
FutureIter_throw(PyObject *op, PyObject *const *args, Py_ssize_t nargs)
1884
0
{
1885
0
    futureiterobject *self = (futureiterobject*)op;
1886
0
    PyObject *type, *val = NULL, *tb = NULL;
1887
0
    if (!_PyArg_CheckPositional("throw", nargs, 1, 3)) {
1888
0
        return NULL;
1889
0
    }
1890
0
    if (nargs > 1) {
1891
0
        if (PyErr_WarnEx(PyExc_DeprecationWarning,
1892
0
                            "the (type, exc, tb) signature of throw() is deprecated, "
1893
0
                            "use the single-arg signature instead.",
1894
0
                            1) < 0) {
1895
0
            return NULL;
1896
0
        }
1897
0
    }
1898
1899
0
    type = args[0];
1900
0
    if (nargs == 3) {
1901
0
        val = args[1];
1902
0
        tb = args[2];
1903
0
    }
1904
0
    else if (nargs == 2) {
1905
0
        val = args[1];
1906
0
    }
1907
1908
0
    if (val == Py_None) {
1909
0
        val = NULL;
1910
0
    }
1911
0
    if (tb == Py_None ) {
1912
0
        tb = NULL;
1913
0
    } else if (tb != NULL && !PyTraceBack_Check(tb)) {
1914
0
        PyErr_SetString(PyExc_TypeError, "throw() third argument must be a traceback");
1915
0
        return NULL;
1916
0
    }
1917
1918
0
    Py_INCREF(type);
1919
0
    Py_XINCREF(val);
1920
0
    Py_XINCREF(tb);
1921
1922
0
    if (PyExceptionClass_Check(type)) {
1923
0
        PyErr_NormalizeException(&type, &val, &tb);
1924
        /* No need to call PyException_SetTraceback since we'll be calling
1925
           PyErr_Restore for `type`, `val`, and `tb`. */
1926
0
    } else if (PyExceptionInstance_Check(type)) {
1927
0
        if (val) {
1928
0
            PyErr_SetString(PyExc_TypeError,
1929
0
                            "instance exception may not have a separate value");
1930
0
            goto fail;
1931
0
        }
1932
0
        val = type;
1933
0
        type = PyExceptionInstance_Class(type);
1934
0
        Py_INCREF(type);
1935
0
        if (tb == NULL)
1936
0
            tb = PyException_GetTraceback(val);
1937
0
    } else {
1938
0
        PyErr_SetString(PyExc_TypeError,
1939
0
                        "exceptions must be classes deriving BaseException or "
1940
0
                        "instances of such a class");
1941
0
        goto fail;
1942
0
    }
1943
1944
0
    Py_BEGIN_CRITICAL_SECTION(self);
1945
0
    Py_CLEAR(self->future);
1946
0
    Py_END_CRITICAL_SECTION();
1947
1948
0
    PyErr_Restore(type, val, tb);
1949
1950
0
    return NULL;
1951
1952
0
  fail:
1953
0
    Py_DECREF(type);
1954
0
    Py_XDECREF(val);
1955
0
    Py_XDECREF(tb);
1956
0
    return NULL;
1957
0
}
1958
1959
static PyObject *
1960
FutureIter_close(PyObject *self, PyObject *arg)
1961
0
{
1962
0
    futureiterobject *it = (futureiterobject*)self;
1963
0
    Py_BEGIN_CRITICAL_SECTION(self);
1964
0
    Py_CLEAR(it->future);
1965
0
    Py_END_CRITICAL_SECTION();
1966
0
    Py_RETURN_NONE;
1967
0
}
1968
1969
static int
1970
FutureIter_clear(PyObject *op)
1971
0
{
1972
0
    futureiterobject *it = (futureiterobject*)op;
1973
0
    Py_CLEAR(it->future);
1974
0
    return 0;
1975
0
}
1976
1977
static int
1978
FutureIter_traverse(PyObject *op, visitproc visit, void *arg)
1979
0
{
1980
0
    futureiterobject *it = (futureiterobject*)op;
1981
0
    Py_VISIT(Py_TYPE(it));
1982
0
    Py_VISIT(it->future);
1983
0
    return 0;
1984
0
}
1985
1986
static PyMethodDef FutureIter_methods[] = {
1987
    {"send",  FutureIter_send, METH_O, NULL},
1988
    {"throw", _PyCFunction_CAST(FutureIter_throw), METH_FASTCALL, NULL},
1989
    {"close", FutureIter_close, METH_NOARGS, NULL},
1990
    {NULL, NULL}        /* Sentinel */
1991
};
1992
1993
static PyObject *
1994
FutureIter_get_fi_future(PyObject *op, void *Py_UNUSED(closure))
1995
0
{
1996
0
    futureiterobject *it = (futureiterobject*)op;
1997
0
    PyObject *fut;
1998
0
    Py_BEGIN_CRITICAL_SECTION(op);
1999
0
    fut = it->future ? Py_NewRef(it->future) : Py_None;
2000
0
    Py_END_CRITICAL_SECTION();
2001
0
    return fut;
2002
0
}
2003
2004
static PyGetSetDef FutureIter_getsetlist[] = {
2005
    {"fi_future", FutureIter_get_fi_future, NULL, NULL},
2006
    {NULL} /* Sentinel */
2007
};
2008
2009
static PyType_Slot FutureIter_slots[] = {
2010
    {Py_tp_dealloc, FutureIter_dealloc},
2011
    {Py_tp_getattro, PyObject_GenericGetAttr},
2012
    {Py_tp_traverse, FutureIter_traverse},
2013
    {Py_tp_clear, FutureIter_clear},
2014
    {Py_tp_iter, PyObject_SelfIter},
2015
    {Py_tp_iternext, FutureIter_iternext},
2016
    {Py_tp_methods, FutureIter_methods},
2017
    {Py_tp_getset, FutureIter_getsetlist},
2018
2019
    // async methods
2020
    {Py_am_send, FutureIter_am_send},
2021
    {0, NULL},
2022
};
2023
2024
static PyType_Spec FutureIter_spec = {
2025
    .name = "_asyncio.FutureIter",
2026
    .basicsize = sizeof(futureiterobject),
2027
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2028
              Py_TPFLAGS_IMMUTABLETYPE),
2029
    .slots = FutureIter_slots,
2030
};
2031
2032
static PyObject *
2033
future_new_iter(PyObject *fut)
2034
0
{
2035
0
    futureiterobject *it;
2036
2037
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
2038
0
    ENSURE_FUTURE_ALIVE(state, fut)
2039
2040
0
    it = _Py_FREELIST_POP(futureiterobject, futureiters);
2041
0
    if (it == NULL) {
2042
0
        it = PyObject_GC_New(futureiterobject, state->FutureIterType);
2043
0
        if (it == NULL) {
2044
0
            return NULL;
2045
0
        }
2046
0
    }
2047
2048
0
    it->future = (FutureObj*)Py_NewRef(fut);
2049
0
    PyObject_GC_Track(it);
2050
0
    return (PyObject*)it;
2051
0
}
2052
2053
2054
/*********************** Task **************************/
2055
2056
2057
/*[clinic input]
2058
class _asyncio.Task "TaskObj *" "&Task_Type"
2059
[clinic start generated code]*/
2060
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=719dcef0fcc03b37]*/
2061
2062
static int task_call_step_soon(asyncio_state *state, TaskObj *, PyObject *);
2063
static PyObject *task_wakeup(PyObject *op, PyObject *arg);
2064
static PyObject *task_step(asyncio_state *, TaskObj *, PyObject *);
2065
static int task_eager_start(_PyThreadStateImpl *ts, asyncio_state *state, TaskObj *task);
2066
2067
/* ----- Task._step wrapper */
2068
2069
static int
2070
TaskStepMethWrapper_clear(PyObject *op)
2071
0
{
2072
0
    TaskStepMethWrapper *o = (TaskStepMethWrapper*)op;
2073
0
    Py_CLEAR(o->sw_task);
2074
0
    Py_CLEAR(o->sw_arg);
2075
0
    return 0;
2076
0
}
2077
2078
static void
2079
TaskStepMethWrapper_dealloc(PyObject *op)
2080
0
{
2081
0
    TaskStepMethWrapper *o = (TaskStepMethWrapper*)op;
2082
0
    PyTypeObject *tp = Py_TYPE(o);
2083
0
    PyObject_GC_UnTrack(o);
2084
0
    (void)TaskStepMethWrapper_clear(op);
2085
0
    Py_TYPE(o)->tp_free(o);
2086
0
    Py_DECREF(tp);
2087
0
}
2088
2089
static PyObject *
2090
TaskStepMethWrapper_call(PyObject *op,
2091
                         PyObject *args, PyObject *kwds)
2092
0
{
2093
0
    TaskStepMethWrapper *o = (TaskStepMethWrapper*)op;
2094
0
    if (kwds != NULL && PyDict_GET_SIZE(kwds) != 0) {
2095
0
        PyErr_SetString(PyExc_TypeError, "function takes no keyword arguments");
2096
0
        return NULL;
2097
0
    }
2098
0
    if (args != NULL && PyTuple_GET_SIZE(args) != 0) {
2099
0
        PyErr_SetString(PyExc_TypeError, "function takes no positional arguments");
2100
0
        return NULL;
2101
0
    }
2102
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)o);
2103
0
    PyObject *res;
2104
0
    Py_BEGIN_CRITICAL_SECTION(o->sw_task);
2105
0
    res = task_step(state, o->sw_task, o->sw_arg);
2106
0
    Py_END_CRITICAL_SECTION();
2107
0
    return res;
2108
0
}
2109
2110
static int
2111
TaskStepMethWrapper_traverse(PyObject *op,
2112
                             visitproc visit, void *arg)
2113
0
{
2114
0
    TaskStepMethWrapper *o = (TaskStepMethWrapper*)op;
2115
0
    Py_VISIT(Py_TYPE(o));
2116
0
    Py_VISIT(o->sw_task);
2117
0
    Py_VISIT(o->sw_arg);
2118
0
    return 0;
2119
0
}
2120
2121
static PyObject *
2122
TaskStepMethWrapper_get___self__(PyObject *op, void *Py_UNUSED(closure))
2123
0
{
2124
0
    TaskStepMethWrapper *o = (TaskStepMethWrapper*)op;
2125
0
    if (o->sw_task) {
2126
0
        return Py_NewRef(o->sw_task);
2127
0
    }
2128
0
    Py_RETURN_NONE;
2129
0
}
2130
2131
static PyGetSetDef TaskStepMethWrapper_getsetlist[] = {
2132
    {"__self__", TaskStepMethWrapper_get___self__, NULL, NULL},
2133
    {NULL} /* Sentinel */
2134
};
2135
2136
static PyType_Slot TaskStepMethWrapper_slots[] = {
2137
    {Py_tp_getset, TaskStepMethWrapper_getsetlist},
2138
    {Py_tp_dealloc, TaskStepMethWrapper_dealloc},
2139
    {Py_tp_call, TaskStepMethWrapper_call},
2140
    {Py_tp_getattro, PyObject_GenericGetAttr},
2141
    {Py_tp_traverse, TaskStepMethWrapper_traverse},
2142
    {Py_tp_clear, TaskStepMethWrapper_clear},
2143
    {0, NULL},
2144
};
2145
2146
static PyType_Spec TaskStepMethWrapper_spec = {
2147
    .name = "_asyncio.TaskStepMethWrapper",
2148
    .basicsize = sizeof(TaskStepMethWrapper),
2149
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2150
              Py_TPFLAGS_IMMUTABLETYPE),
2151
    .slots = TaskStepMethWrapper_slots,
2152
};
2153
2154
static PyObject *
2155
TaskStepMethWrapper_new(TaskObj *task, PyObject *arg)
2156
0
{
2157
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)task);
2158
0
    TaskStepMethWrapper *o;
2159
0
    o = PyObject_GC_New(TaskStepMethWrapper, state->TaskStepMethWrapper_Type);
2160
0
    if (o == NULL) {
2161
0
        return NULL;
2162
0
    }
2163
2164
0
    o->sw_task = (TaskObj*)Py_NewRef(task);
2165
0
    o->sw_arg = Py_XNewRef(arg);
2166
2167
0
    PyObject_GC_Track(o);
2168
0
    return (PyObject*) o;
2169
0
}
2170
2171
/* ----- Task._wakeup implementation */
2172
2173
static  PyMethodDef TaskWakeupDef = {
2174
    "task_wakeup",
2175
    task_wakeup,
2176
    METH_O,
2177
    NULL
2178
};
2179
2180
/* ----- Task introspection helpers */
2181
2182
static void
2183
register_task(_PyThreadStateImpl *ts, TaskObj *task)
2184
0
{
2185
0
    if (task->task_node.next != NULL) {
2186
        // already registered
2187
0
        assert(task->task_node.prev != NULL);
2188
0
        return;
2189
0
    }
2190
#ifdef Py_GIL_DISABLED
2191
    task->task_tstate_id = ts->base.id;
2192
#endif
2193
0
    struct llist_node *head = &ts->asyncio_tasks_head;
2194
0
    llist_insert_tail(head, &task->task_node);
2195
0
}
2196
2197
static inline void
2198
unregister_task_safe(TaskObj *task)
2199
0
{
2200
0
    if (task->task_node.next == NULL) {
2201
        // not registered
2202
0
        assert(task->task_node.prev == NULL);
2203
0
        return;
2204
0
    }
2205
0
    llist_remove(&task->task_node);
2206
0
}
2207
2208
static void
2209
unregister_task(TaskObj *task)
2210
0
{
2211
#ifdef Py_GIL_DISABLED
2212
    PyThreadState *tstate = _PyThreadState_GET();
2213
    // The task can only be on this thread's list if this thread state
2214
    // registered it, in which case no locking is needed.
2215
    if (task->task_tstate_id == tstate->id) {
2216
        unregister_task_safe(task);
2217
    }
2218
    else {
2219
        // The task is on another thread's list or on the interpreter's
2220
        // list of lingering tasks: stop the world to remove it.
2221
        _PyEval_StopTheWorld(tstate->interp);
2222
        unregister_task_safe(task);
2223
        _PyEval_StartTheWorld(tstate->interp);
2224
    }
2225
#else
2226
0
    unregister_task_safe(task);
2227
0
#endif
2228
0
}
2229
2230
static int
2231
enter_task(_PyThreadStateImpl *ts, PyObject *loop, PyObject *task)
2232
0
{
2233
0
    if (ts->asyncio_running_loop != loop) {
2234
0
        PyErr_Format(PyExc_RuntimeError, "loop %R is not the running loop", loop);
2235
0
        return -1;
2236
0
    }
2237
2238
0
    if (ts->asyncio_running_task != NULL) {
2239
0
        PyErr_Format(
2240
0
            PyExc_RuntimeError,
2241
0
            "Cannot enter into task %R while another " \
2242
0
            "task %R is being executed.",
2243
0
            task, ts->asyncio_running_task);
2244
0
        return -1;
2245
0
    }
2246
2247
0
    ts->asyncio_running_task = Py_NewRef(task);
2248
0
    return 0;
2249
0
}
2250
2251
static int
2252
leave_task(_PyThreadStateImpl *ts, PyObject *loop, PyObject *task)
2253
0
{
2254
0
    if (ts->asyncio_running_loop != loop) {
2255
0
        PyErr_Format(PyExc_RuntimeError, "loop %R is not the running loop", loop);
2256
0
        return -1;
2257
0
    }
2258
2259
0
    if (ts->asyncio_running_task != task) {
2260
0
        PyErr_Format(
2261
0
            PyExc_RuntimeError,
2262
0
            "Invalid attempt to leave task %R while " \
2263
0
            "task %R is entered.",
2264
0
            task, ts->asyncio_running_task ? ts->asyncio_running_task : Py_None);
2265
0
        return -1;
2266
0
    }
2267
0
    Py_CLEAR(ts->asyncio_running_task);
2268
0
    return 0;
2269
0
}
2270
2271
static PyObject *
2272
swap_current_task(_PyThreadStateImpl *ts, PyObject *loop, PyObject *task)
2273
0
{
2274
0
    if (ts->asyncio_running_loop != loop) {
2275
0
        PyErr_Format(PyExc_RuntimeError, "loop %R is not the running loop", loop);
2276
0
        return NULL;
2277
0
    }
2278
2279
    /* transfer ownership to avoid redundant ref counting */
2280
0
    PyObject *prev_task = ts->asyncio_running_task;
2281
0
    if (task != Py_None) {
2282
0
        ts->asyncio_running_task = Py_NewRef(task);
2283
0
    } else {
2284
0
        ts->asyncio_running_task = NULL;
2285
0
    }
2286
0
    if (prev_task == NULL) {
2287
0
        Py_RETURN_NONE;
2288
0
    }
2289
0
    return prev_task;
2290
0
}
2291
2292
/* ----- Task */
2293
2294
/*[clinic input]
2295
@vectorcall
2296
_asyncio.Task.__init__
2297
2298
    coro: object
2299
    *
2300
    loop: object = None
2301
    name: object = None
2302
    context: object = None
2303
    eager_start: bool = False
2304
2305
A coroutine wrapped in a Future.
2306
[clinic start generated code]*/
2307
2308
static int
2309
_asyncio_Task___init___impl(TaskObj *self, PyObject *coro, PyObject *loop,
2310
                            PyObject *name, PyObject *context,
2311
                            int eager_start)
2312
/*[clinic end generated code: output=7aced2d27836f1a1 input=de87c52b0800ab4b]*/
2313
0
{
2314
0
    if (future_init((FutureObj*)self, loop)) {
2315
0
        return -1;
2316
0
    }
2317
0
    self->task_is_task = 1;
2318
2319
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
2320
0
    int is_coro = is_coroutine(state, coro);
2321
0
    if (is_coro == -1) {
2322
0
        return -1;
2323
0
    }
2324
0
    if (is_coro == 0) {
2325
0
        self->task_log_destroy_pending = 0;
2326
0
        PyErr_Format(PyExc_TypeError,
2327
0
                     "a coroutine was expected, got %R",
2328
0
                     coro);
2329
0
        return -1;
2330
0
    }
2331
2332
0
    if (context == Py_None) {
2333
0
        Py_XSETREF(self->task_context, PyContext_CopyCurrent());
2334
0
        if (self->task_context == NULL) {
2335
0
            return -1;
2336
0
        }
2337
0
    } else if (!PyContext_CheckExact(context)) {
2338
        // gh-157301: the passed value must be a contextvars.Context
2339
0
        self->task_log_destroy_pending = 0;
2340
0
        PyErr_Format(PyExc_TypeError,
2341
0
                     "a contextvars.Context was expected, got %T",
2342
0
                     context);
2343
0
        return -1;
2344
0
    } else {
2345
0
        Py_XSETREF(self->task_context, Py_NewRef(context));
2346
0
    }
2347
2348
0
    Py_CLEAR(self->task_fut_waiter);
2349
0
    self->task_must_cancel = 0;
2350
0
    self->task_log_destroy_pending = 1;
2351
0
    self->task_num_cancels_requested = 0;
2352
0
    set_task_coro(self, coro);
2353
2354
0
    if (name == Py_None) {
2355
        // optimization: defer task name formatting
2356
        // store the task counter as PyLong in the name
2357
        // for deferred formatting in get_name
2358
#ifdef Py_GIL_DISABLED
2359
        unsigned long long counter = _Py_atomic_add_uint64_relaxed(&state->task_name_counter, 1) + 1;
2360
#else
2361
0
        unsigned long long counter = ++state->task_name_counter;
2362
0
#endif
2363
0
        name = PyLong_FromUnsignedLongLong(counter);
2364
0
    } else if (!PyUnicode_CheckExact(name)) {
2365
0
        name = PyObject_Str(name);
2366
0
    } else {
2367
0
        Py_INCREF(name);
2368
0
    }
2369
0
    Py_XSETREF(self->task_name, name);
2370
0
    if (self->task_name == NULL) {
2371
0
        return -1;
2372
0
    }
2373
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
2374
#ifdef Py_GIL_DISABLED
2375
    // This is required so that _Py_TryIncref(self)
2376
    // works correctly in non-owning threads.
2377
    _PyObject_SetMaybeWeakref((PyObject *)self);
2378
#endif
2379
0
    if (eager_start) {
2380
        // gh-154695: loop may be None here, future_init() resolved it into task_loop.
2381
0
        PyObject *res = PyObject_CallMethodNoArgs(self->task_loop,
2382
0
                                                  &_Py_ID(is_running));
2383
0
        if (res == NULL) {
2384
0
            return -1;
2385
0
        }
2386
0
        int is_loop_running = Py_IsTrue(res);
2387
0
        Py_DECREF(res);
2388
0
        if (is_loop_running) {
2389
0
            if (task_eager_start(ts, state, self)) {
2390
0
                return -1;
2391
0
            }
2392
0
            return 0;
2393
0
        }
2394
0
    }
2395
2396
0
    if (task_call_step_soon(state, self, NULL)) {
2397
0
        return -1;
2398
0
    }
2399
0
    register_task(ts, self);
2400
0
    return 0;
2401
0
}
2402
2403
static int
2404
TaskObj_clear(PyObject *op)
2405
0
{
2406
0
    TaskObj *task = (TaskObj*)op;
2407
0
    (void)FutureObj_clear(op);
2408
0
    clear_task_coro(task);
2409
0
    Py_CLEAR(task->task_context);
2410
0
    Py_CLEAR(task->task_name);
2411
0
    Py_CLEAR(task->task_fut_waiter);
2412
0
    return 0;
2413
0
}
2414
2415
static int
2416
TaskObj_traverse(PyObject *op, visitproc visit, void *arg)
2417
0
{
2418
0
    TaskObj *task = (TaskObj*)op;
2419
0
    Py_VISIT(Py_TYPE(task));
2420
0
    Py_VISIT(task->task_context);
2421
0
    Py_VISIT(task->task_coro);
2422
0
    Py_VISIT(task->task_name);
2423
0
    Py_VISIT(task->task_fut_waiter);
2424
0
    FutureObj *fut = (FutureObj *)task;
2425
0
    Py_VISIT(fut->fut_loop);
2426
0
    Py_VISIT(fut->fut_callback0);
2427
0
    Py_VISIT(fut->fut_context0);
2428
0
    Py_VISIT(fut->fut_callbacks);
2429
0
    Py_VISIT(fut->fut_result);
2430
0
    Py_VISIT(fut->fut_exception);
2431
0
    Py_VISIT(fut->fut_exception_tb);
2432
0
    Py_VISIT(fut->fut_source_tb);
2433
0
    Py_VISIT(fut->fut_cancel_msg);
2434
0
    Py_VISIT(fut->fut_cancelled_exc);
2435
0
    Py_VISIT(fut->fut_awaited_by);
2436
0
    return PyObject_VisitManagedDict((PyObject *)fut, visit, arg);
2437
0
}
2438
2439
/*[clinic input]
2440
@critical_section
2441
@getter
2442
_asyncio.Task._log_destroy_pending -> bool
2443
[clinic start generated code]*/
2444
2445
static int
2446
_asyncio_Task__log_destroy_pending_get_impl(TaskObj *self)
2447
/*[clinic end generated code: output=98b5f7bad24a2381 input=a87002bdf72e380b]*/
2448
0
{
2449
0
    return self->task_log_destroy_pending;
2450
0
}
2451
2452
/*[clinic input]
2453
@critical_section
2454
@setter
2455
_asyncio.Task._log_destroy_pending
2456
    value: bool
2457
[clinic start generated code]*/
2458
2459
static int
2460
_asyncio_Task__log_destroy_pending_set_impl(TaskObj *self, int value)
2461
/*[clinic end generated code: output=132bbf2b4c627777 input=533fea7776daa075]*/
2462
0
{
2463
0
    self->task_log_destroy_pending = value;
2464
0
    return 0;
2465
0
}
2466
2467
2468
/*[clinic input]
2469
@critical_section
2470
@getter
2471
_asyncio.Task._must_cancel
2472
[clinic start generated code]*/
2473
2474
static PyObject *
2475
_asyncio_Task__must_cancel_get_impl(TaskObj *self)
2476
/*[clinic end generated code: output=70e79b900996c363 input=2d04529fb23feedf]*/
2477
0
{
2478
0
    if (self->task_must_cancel) {
2479
0
        Py_RETURN_TRUE;
2480
0
    }
2481
0
    else {
2482
0
        Py_RETURN_FALSE;
2483
0
    }
2484
0
}
2485
2486
/*[clinic input]
2487
@critical_section
2488
@getter
2489
_asyncio.Task._coro
2490
[clinic start generated code]*/
2491
2492
static PyObject *
2493
_asyncio_Task__coro_get_impl(TaskObj *self)
2494
/*[clinic end generated code: output=a2726012ab5fd531 input=323c31a272020624]*/
2495
0
{
2496
0
    if (self->task_coro) {
2497
0
        return Py_NewRef(self->task_coro);
2498
0
    }
2499
2500
0
    Py_RETURN_NONE;
2501
0
}
2502
2503
2504
/*[clinic input]
2505
@critical_section
2506
@getter
2507
_asyncio.Task._fut_waiter
2508
[clinic start generated code]*/
2509
2510
static PyObject *
2511
_asyncio_Task__fut_waiter_get_impl(TaskObj *self)
2512
/*[clinic end generated code: output=c4f966b847fefcdf input=4d1005d725e72db7]*/
2513
0
{
2514
0
    if (self->task_fut_waiter) {
2515
0
        return Py_NewRef(self->task_fut_waiter);
2516
0
    }
2517
2518
0
    Py_RETURN_NONE;
2519
0
}
2520
2521
static PyObject *
2522
TaskObj_repr(PyObject *task)
2523
0
{
2524
0
    asyncio_state *state = get_asyncio_state_by_def(task);
2525
0
    return PyObject_CallOneArg(state->asyncio_task_repr_func, task);
2526
0
}
2527
2528
2529
/*[clinic input]
2530
@critical_section
2531
_asyncio.Task._make_cancelled_error
2532
2533
Create the CancelledError to raise if the Task is cancelled.
2534
2535
This should only be called once when handling a cancellation since
2536
it erases the context exception value.
2537
[clinic start generated code]*/
2538
2539
static PyObject *
2540
_asyncio_Task__make_cancelled_error_impl(TaskObj *self)
2541
/*[clinic end generated code: output=55a819e8b4276fab input=2d3213be0cb02390]*/
2542
0
{
2543
0
    FutureObj *fut = (FutureObj*)self;
2544
0
    return _asyncio_Future__make_cancelled_error_impl(fut);
2545
0
}
2546
2547
2548
/*[clinic input]
2549
@critical_section
2550
_asyncio.Task.cancel
2551
2552
    msg: object = None
2553
2554
Request that this task cancel itself.
2555
2556
This arranges for a CancelledError to be thrown into the
2557
wrapped coroutine on the next cycle through the event loop.
2558
The coroutine then has a chance to clean up or even deny
2559
the request using try/except/finally.
2560
2561
Unlike Future.cancel, this does not guarantee that the
2562
task will be cancelled: the exception might be caught and
2563
acted upon, delaying cancellation of the task or preventing
2564
cancellation completely.  The task may also return a value or
2565
raise a different exception.
2566
2567
Immediately after this method is called, Task.cancelled() will
2568
not return True (unless the task was already cancelled).  A
2569
task will be marked as cancelled when the wrapped coroutine
2570
terminates with a CancelledError exception (even if cancel()
2571
was not called).
2572
2573
This also increases the task's count of cancellation requests.
2574
[clinic start generated code]*/
2575
2576
static PyObject *
2577
_asyncio_Task_cancel_impl(TaskObj *self, PyObject *msg)
2578
/*[clinic end generated code: output=c66b60d41c74f9f1 input=6125d45b9a6a5abd]*/
2579
0
{
2580
0
    self->task_log_tb = 0;
2581
2582
0
    if (self->task_state != STATE_PENDING) {
2583
0
        Py_RETURN_FALSE;
2584
0
    }
2585
2586
0
    self->task_num_cancels_requested += 1;
2587
2588
    // These three lines are controversial.  See discussion starting at
2589
    // https://github.com/python/cpython/pull/31394#issuecomment-1053545331
2590
    // and corresponding code in tasks.py.
2591
    // if (self->task_num_cancels_requested > 1) {
2592
    //     Py_RETURN_FALSE;
2593
    // }
2594
2595
0
    if (self->task_fut_waiter) {
2596
0
        PyObject *res;
2597
0
        int is_true;
2598
2599
0
        res = PyObject_CallMethodOneArg(self->task_fut_waiter,
2600
0
                                           &_Py_ID(cancel), msg);
2601
0
        if (res == NULL) {
2602
0
            return NULL;
2603
0
        }
2604
2605
0
        is_true = PyObject_IsTrue(res);
2606
0
        Py_DECREF(res);
2607
0
        if (is_true < 0) {
2608
0
            return NULL;
2609
0
        }
2610
2611
0
        if (is_true) {
2612
0
            Py_RETURN_TRUE;
2613
0
        }
2614
0
    }
2615
2616
0
    self->task_must_cancel = 1;
2617
0
    Py_XINCREF(msg);
2618
0
    Py_XSETREF(self->task_cancel_msg, msg);
2619
0
    Py_RETURN_TRUE;
2620
0
}
2621
2622
/*[clinic input]
2623
@critical_section
2624
_asyncio.Task.cancelling
2625
2626
Return the count of the task's cancellation requests.
2627
2628
This count is incremented when .cancel() is called
2629
and may be decremented using .uncancel().
2630
[clinic start generated code]*/
2631
2632
static PyObject *
2633
_asyncio_Task_cancelling_impl(TaskObj *self)
2634
/*[clinic end generated code: output=803b3af96f917d7e input=5ef89b1b38f080ee]*/
2635
/*[clinic end generated code]*/
2636
0
{
2637
0
    return PyLong_FromLong(self->task_num_cancels_requested);
2638
0
}
2639
2640
/*[clinic input]
2641
@critical_section
2642
_asyncio.Task.uncancel
2643
2644
Decrement the task's count of cancellation requests.
2645
2646
This should be used by tasks that catch CancelledError
2647
and wish to continue indefinitely until they are cancelled again.
2648
2649
Returns the remaining number of cancellation requests.
2650
[clinic start generated code]*/
2651
2652
static PyObject *
2653
_asyncio_Task_uncancel_impl(TaskObj *self)
2654
/*[clinic end generated code: output=58184d236a817d3c input=cb3220b0e5afd61d]*/
2655
/*[clinic end generated code]*/
2656
0
{
2657
0
    if (self->task_num_cancels_requested > 0) {
2658
0
        self->task_num_cancels_requested -= 1;
2659
0
        if (self->task_num_cancels_requested == 0) {
2660
0
            self->task_must_cancel = 0;
2661
0
        }
2662
0
    }
2663
0
    return PyLong_FromLong(self->task_num_cancels_requested);
2664
0
}
2665
2666
/*[clinic input]
2667
_asyncio.Task.get_stack
2668
2669
    cls: defining_class
2670
    /
2671
    *
2672
    limit: object = None
2673
2674
Return the list of stack frames for this task's coroutine.
2675
2676
If the coroutine is not done, this returns the stack where it is
2677
suspended.  If the coroutine has completed successfully or was
2678
cancelled, this returns an empty list.  If the coroutine was
2679
terminated by an exception, this returns the list of traceback
2680
frames.
2681
2682
The frames are always ordered from oldest to newest.
2683
2684
The optional limit gives the maximum number of frames to
2685
return; by default all available frames are returned.  Its
2686
meaning differs depending on whether a stack or a traceback is
2687
returned: the newest frames of a stack are returned, but the
2688
oldest frames of a traceback are returned.  (This matches the
2689
behavior of the traceback module.)
2690
2691
For reasons beyond our control, only one stack frame is
2692
returned for a suspended coroutine.
2693
[clinic start generated code]*/
2694
2695
static PyObject *
2696
_asyncio_Task_get_stack_impl(TaskObj *self, PyTypeObject *cls,
2697
                             PyObject *limit)
2698
/*[clinic end generated code: output=6774dfc10d3857fa input=8e01c9b2618ae953]*/
2699
0
{
2700
0
    asyncio_state *state = get_asyncio_state_by_cls(cls);
2701
0
    PyObject *stack[] = {(PyObject *)self, limit};
2702
0
    return PyObject_Vectorcall(state->asyncio_task_get_stack_func,
2703
0
                               stack, 2, NULL);
2704
0
}
2705
2706
/*[clinic input]
2707
_asyncio.Task.print_stack
2708
2709
    cls: defining_class
2710
    /
2711
    *
2712
    limit: object = None
2713
    file: object = None
2714
2715
Print the stack or traceback for this task's coroutine.
2716
2717
This produces output similar to that of the traceback module,
2718
for the frames retrieved by get_stack().  The limit argument
2719
is passed to get_stack().  The file argument is an I/O stream
2720
to which the output is written; by default output is written
2721
to sys.stderr.
2722
[clinic start generated code]*/
2723
2724
static PyObject *
2725
_asyncio_Task_print_stack_impl(TaskObj *self, PyTypeObject *cls,
2726
                               PyObject *limit, PyObject *file)
2727
/*[clinic end generated code: output=b38affe9289ec826 input=150b35ba2d3a7dee]*/
2728
0
{
2729
0
    asyncio_state *state = get_asyncio_state_by_cls(cls);
2730
0
    PyObject *stack[] = {(PyObject *)self, limit, file};
2731
0
    return PyObject_Vectorcall(state->asyncio_task_print_stack_func,
2732
0
                               stack, 3, NULL);
2733
0
}
2734
2735
/*[clinic input]
2736
_asyncio.Task.set_result
2737
2738
    result: object
2739
    /
2740
[clinic start generated code]*/
2741
2742
static PyObject *
2743
_asyncio_Task_set_result_impl(TaskObj *self, PyObject *result)
2744
/*[clinic end generated code: output=e9d8e3cdaf18e258 input=9d1a00c07be41bab]*/
2745
0
{
2746
0
    PyErr_SetString(PyExc_RuntimeError,
2747
0
                    "Task does not support set_result operation");
2748
0
    return NULL;
2749
0
}
2750
2751
/*[clinic input]
2752
_asyncio.Task.set_exception
2753
2754
    exception: object
2755
    /
2756
[clinic start generated code]*/
2757
2758
static PyObject *
2759
_asyncio_Task_set_exception_impl(TaskObj *self, PyObject *exception)
2760
/*[clinic end generated code: output=96a91790c192cc7d input=9a8f65c83dcf893a]*/
2761
0
{
2762
0
    PyErr_SetString(PyExc_RuntimeError,
2763
0
                    "Task does not support set_exception operation");
2764
0
    return NULL;
2765
0
}
2766
2767
/*[clinic input]
2768
@critical_section
2769
_asyncio.Task.get_coro
2770
[clinic start generated code]*/
2771
2772
static PyObject *
2773
_asyncio_Task_get_coro_impl(TaskObj *self)
2774
/*[clinic end generated code: output=bcac27c8cc6c8073 input=a47f81427e39fe0c]*/
2775
0
{
2776
0
    if (self->task_coro) {
2777
0
        return Py_NewRef(self->task_coro);
2778
0
    }
2779
2780
0
    Py_RETURN_NONE;
2781
0
}
2782
2783
/*[clinic input]
2784
_asyncio.Task.get_context
2785
[clinic start generated code]*/
2786
2787
static PyObject *
2788
_asyncio_Task_get_context_impl(TaskObj *self)
2789
/*[clinic end generated code: output=6996f53d3dc01aef input=87c0b209b8fceeeb]*/
2790
0
{
2791
0
    if (self->task_context) {
2792
0
        return Py_NewRef(self->task_context);
2793
0
    }
2794
2795
0
    Py_RETURN_NONE;
2796
0
}
2797
2798
/*[clinic input]
2799
@critical_section
2800
_asyncio.Task.get_name
2801
[clinic start generated code]*/
2802
2803
static PyObject *
2804
_asyncio_Task_get_name_impl(TaskObj *self)
2805
/*[clinic end generated code: output=0ecf1570c3b37a8f input=92a8f30c85034249]*/
2806
0
{
2807
0
    if (self->task_name) {
2808
0
        if (PyLong_CheckExact(self->task_name)) {
2809
            // Formatting can run arbitrary code (e.g. a GC finalizer that logs
2810
            // and re-enters get_name()), which may replace self->task_name.
2811
            // Hold a strong reference to the counter while formatting it.
2812
0
            PyObject *counter = Py_NewRef(self->task_name);
2813
0
            PyObject *name = PyUnicode_FromFormat("Task-%S", counter);
2814
0
            Py_DECREF(counter);
2815
0
            if (name == NULL) {
2816
0
                return NULL;
2817
0
            }
2818
0
            Py_SETREF(self->task_name, name);
2819
0
        }
2820
0
        return Py_NewRef(self->task_name);
2821
0
    }
2822
2823
0
    Py_RETURN_NONE;
2824
0
}
2825
2826
/*[clinic input]
2827
@critical_section
2828
_asyncio.Task.set_name
2829
2830
    value: object
2831
    /
2832
[clinic start generated code]*/
2833
2834
static PyObject *
2835
_asyncio_Task_set_name_impl(TaskObj *self, PyObject *value)
2836
/*[clinic end generated code: output=f88ff4c0d64a9a6f input=e8d400ad64bad799]*/
2837
0
{
2838
0
    if (!PyUnicode_CheckExact(value)) {
2839
0
        value = PyObject_Str(value);
2840
0
        if (value == NULL) {
2841
0
            return NULL;
2842
0
        }
2843
0
    } else {
2844
0
        Py_INCREF(value);
2845
0
    }
2846
2847
0
    Py_XSETREF(self->task_name, value);
2848
0
    Py_RETURN_NONE;
2849
0
}
2850
2851
static void
2852
TaskObj_finalize(PyObject *op)
2853
0
{
2854
0
    TaskObj *task = (TaskObj*)op;
2855
0
    PyObject *context;
2856
0
    PyObject *message = NULL;
2857
0
    PyObject *func;
2858
2859
0
    if (task->task_state != STATE_PENDING || !task->task_log_destroy_pending) {
2860
0
        goto done;
2861
0
    }
2862
2863
    /* Save the current exception, if any. */
2864
0
    PyObject *exc = PyErr_GetRaisedException();
2865
2866
0
    context = PyDict_New();
2867
0
    if (context == NULL) {
2868
0
        goto finally;
2869
0
    }
2870
2871
0
    message = PyUnicode_FromString("Task was destroyed but it is pending!");
2872
0
    if (message == NULL) {
2873
0
        goto finally;
2874
0
    }
2875
2876
0
    if (PyDict_SetItem(context, &_Py_ID(message), message) < 0 ||
2877
0
        PyDict_SetItem(context, &_Py_ID(task), (PyObject*)task) < 0)
2878
0
    {
2879
0
        goto finally;
2880
0
    }
2881
2882
0
    if (task->task_source_tb != NULL) {
2883
0
        if (PyDict_SetItem(context, &_Py_ID(source_traceback),
2884
0
                              task->task_source_tb) < 0)
2885
0
        {
2886
0
            goto finally;
2887
0
        }
2888
0
    }
2889
2890
0
    func = PyObject_GetAttr(task->task_loop, &_Py_ID(call_exception_handler));
2891
0
    if (func != NULL) {
2892
0
        PyObject *res = PyObject_CallOneArg(func, context);
2893
0
        if (res == NULL) {
2894
0
            PyErr_FormatUnraisable("Exception ignored while calling asyncio "
2895
0
                                   "function %R", func);
2896
0
        }
2897
0
        else {
2898
0
            Py_DECREF(res);
2899
0
        }
2900
0
        Py_DECREF(func);
2901
0
    }
2902
2903
0
finally:
2904
0
    Py_XDECREF(context);
2905
0
    Py_XDECREF(message);
2906
2907
    /* Restore the saved exception. */
2908
0
    PyErr_SetRaisedException(exc);
2909
2910
0
done:
2911
0
    FutureObj_finalize((PyObject*)task);
2912
0
}
2913
2914
static void TaskObj_dealloc(PyObject *);  /* Needs Task_CheckExact */
2915
2916
static PyMethodDef TaskType_methods[] = {
2917
    _ASYNCIO_FUTURE_RESULT_METHODDEF
2918
    _ASYNCIO_FUTURE_EXCEPTION_METHODDEF
2919
    _ASYNCIO_FUTURE_ADD_DONE_CALLBACK_METHODDEF
2920
    _ASYNCIO_FUTURE_REMOVE_DONE_CALLBACK_METHODDEF
2921
    _ASYNCIO_FUTURE_CANCELLED_METHODDEF
2922
    _ASYNCIO_FUTURE_DONE_METHODDEF
2923
    _ASYNCIO_TASK_SET_RESULT_METHODDEF
2924
    _ASYNCIO_TASK_SET_EXCEPTION_METHODDEF
2925
    _ASYNCIO_TASK_CANCEL_METHODDEF
2926
    _ASYNCIO_TASK_CANCELLING_METHODDEF
2927
    _ASYNCIO_TASK_UNCANCEL_METHODDEF
2928
    _ASYNCIO_TASK_GET_STACK_METHODDEF
2929
    _ASYNCIO_TASK_PRINT_STACK_METHODDEF
2930
    _ASYNCIO_TASK__MAKE_CANCELLED_ERROR_METHODDEF
2931
    _ASYNCIO_TASK_GET_NAME_METHODDEF
2932
    _ASYNCIO_TASK_SET_NAME_METHODDEF
2933
    _ASYNCIO_TASK_GET_CORO_METHODDEF
2934
    _ASYNCIO_TASK_GET_CONTEXT_METHODDEF
2935
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
2936
    PyDoc_STR("Tasks are generic over the return type of their wrapped coroutines")},
2937
    {NULL, NULL}        /* Sentinel */
2938
};
2939
2940
static PyGetSetDef TaskType_getsetlist[] = {
2941
    _ASYNCIO_TASK__LOG_DESTROY_PENDING_GETSETDEF
2942
    _ASYNCIO_TASK__MUST_CANCEL_GETSETDEF
2943
    _ASYNCIO_TASK__CORO_GETSETDEF
2944
    _ASYNCIO_TASK__FUT_WAITER_GETSETDEF
2945
    {NULL} /* Sentinel */
2946
};
2947
2948
static PyType_Slot Task_slots[] = {
2949
    {Py_tp_dealloc, TaskObj_dealloc},
2950
    {Py_tp_repr, TaskObj_repr},
2951
    {Py_tp_doc, (void *)_asyncio_Task___init____doc__},
2952
    {Py_tp_traverse, TaskObj_traverse},
2953
    {Py_tp_clear, TaskObj_clear},
2954
    {Py_tp_iter, future_new_iter},
2955
    {Py_tp_methods, TaskType_methods},
2956
    {Py_tp_getset, TaskType_getsetlist},
2957
    {Py_tp_init, _asyncio_Task___init__},
2958
    {Py_tp_vectorcall, _asyncio_Task_vectorcall},
2959
    {Py_tp_new, PyType_GenericNew},
2960
    {Py_tp_finalize, TaskObj_finalize},
2961
2962
    // async slots
2963
    {Py_am_await, future_new_iter},
2964
    {0, NULL},
2965
};
2966
2967
static PyType_Spec Task_spec = {
2968
    .name = "_asyncio.Task",
2969
    .basicsize = sizeof(TaskObj),
2970
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE |
2971
              Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_MANAGED_DICT |
2972
              Py_TPFLAGS_MANAGED_WEAKREF),
2973
    .slots = Task_slots,
2974
};
2975
2976
static void
2977
TaskObj_dealloc(PyObject *self)
2978
0
{
2979
0
    if (PyObject_CallFinalizerFromDealloc(self) < 0) {
2980
0
        return; // resurrected
2981
0
    }
2982
    // Untrack the object before unregistering the task, since the
2983
    // latter can cause a stop-the-world pause, after which another
2984
    // thread might call the GC and reach the object while it is
2985
    // semi-deallocated but still tracked
2986
0
    PyObject_GC_UnTrack(self);
2987
2988
    // unregister the task after finalization so that
2989
    // if the task gets resurrected, it remains registered
2990
0
    unregister_task((TaskObj *)self);
2991
2992
0
    PyTypeObject *tp = Py_TYPE(self);
2993
0
    PyObject_ClearWeakRefs(self);
2994
2995
0
    (void)TaskObj_clear(self);
2996
0
    tp->tp_free(self);
2997
0
    Py_DECREF(tp);
2998
0
}
2999
3000
static int
3001
task_call_step_soon(asyncio_state *state, TaskObj *task, PyObject *arg)
3002
0
{
3003
0
    PyObject *cb = TaskStepMethWrapper_new(task, arg);
3004
0
    if (cb == NULL) {
3005
0
        return -1;
3006
0
    }
3007
3008
0
    int ret = call_soon(state, task->task_loop, cb, NULL, task->task_context);
3009
0
    Py_DECREF(cb);
3010
0
    return ret;
3011
0
}
3012
3013
static PyObject *
3014
task_set_error_soon(asyncio_state *state, TaskObj *task, PyObject *et,
3015
                    const char *format, ...)
3016
0
{
3017
0
    PyObject* msg;
3018
3019
0
    va_list vargs;
3020
0
    va_start(vargs, format);
3021
0
    msg = PyUnicode_FromFormatV(format, vargs);
3022
0
    va_end(vargs);
3023
3024
0
    if (msg == NULL) {
3025
0
        return NULL;
3026
0
    }
3027
3028
0
    PyObject *e = PyObject_CallOneArg(et, msg);
3029
0
    Py_DECREF(msg);
3030
0
    if (e == NULL) {
3031
0
        return NULL;
3032
0
    }
3033
3034
0
    if (task_call_step_soon(state, task, e) == -1) {
3035
0
        Py_DECREF(e);
3036
0
        return NULL;
3037
0
    }
3038
3039
0
    Py_DECREF(e);
3040
0
    Py_RETURN_NONE;
3041
0
}
3042
3043
static inline int
3044
gen_status_from_result(PyObject **result)
3045
0
{
3046
0
    if (*result != NULL) {
3047
0
        return PYGEN_NEXT;
3048
0
    }
3049
0
    if (_PyGen_FetchStopIterationValue(result) == 0) {
3050
0
        return PYGEN_RETURN;
3051
0
    }
3052
3053
0
    assert(PyErr_Occurred());
3054
0
    return PYGEN_ERROR;
3055
0
}
3056
3057
static PyObject *
3058
task_step_impl(asyncio_state *state, TaskObj *task, PyObject *exc)
3059
0
{
3060
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(task);
3061
3062
0
    int clear_exc = 0;
3063
0
    PyObject *result = NULL;
3064
0
    PyObject *coro;
3065
0
    PyObject *o;
3066
3067
0
    if (task->task_state != STATE_PENDING) {
3068
0
        PyErr_Format(state->asyncio_InvalidStateError,
3069
0
                     "__step(): already done: %R %R",
3070
0
                     task,
3071
0
                     exc ? exc : Py_None);
3072
0
        goto fail;
3073
0
    }
3074
3075
0
    if (task->task_must_cancel) {
3076
0
        assert(exc != Py_None);
3077
3078
        /* Replace exc with a CancelledError unless it already is one, or
3079
        it is SystemExit/KeyboardInterrupt, which must propagate
3080
        unchanged (gh-108549). */
3081
0
        if (!exc ||
3082
0
            (!PyErr_GivenExceptionMatches(exc, state->asyncio_CancelledError) &&
3083
0
            !PyErr_GivenExceptionMatches(exc, PyExc_KeyboardInterrupt) &&
3084
0
            !PyErr_GivenExceptionMatches(exc, PyExc_SystemExit))) {
3085
0
            exc = create_cancelled_error(state, (FutureObj*)task);
3086
3087
0
            if (!exc) {
3088
0
                goto fail;
3089
0
            }
3090
0
            clear_exc = 1;
3091
0
        }
3092
3093
0
        task->task_must_cancel = 0;
3094
0
    }
3095
3096
0
    Py_CLEAR(task->task_fut_waiter);
3097
3098
0
    coro = task->task_coro;
3099
0
    if (coro == NULL) {
3100
0
        PyErr_SetString(PyExc_RuntimeError, "uninitialized Task object");
3101
0
        if (clear_exc) {
3102
            /* We created 'exc' during this call */
3103
0
            Py_DECREF(exc);
3104
0
        }
3105
0
        return NULL;
3106
0
    }
3107
3108
0
    int gen_status = PYGEN_ERROR;
3109
0
    if (exc == NULL) {
3110
0
        gen_status = PyIter_Send(coro, Py_None, &result);
3111
0
    }
3112
0
    else {
3113
0
        result = PyObject_CallMethodOneArg(coro, &_Py_ID(throw), exc);
3114
0
        gen_status = gen_status_from_result(&result);
3115
0
        if (clear_exc) {
3116
            /* We created 'exc' during this call */
3117
0
            Py_DECREF(exc);
3118
0
        }
3119
0
    }
3120
3121
0
    if (gen_status == PYGEN_RETURN || gen_status == PYGEN_ERROR) {
3122
0
        if (result != NULL) {
3123
            /* The error is StopIteration and that means that
3124
               the underlying coroutine has resolved */
3125
3126
0
            PyObject *tmp;
3127
0
            if (task->task_must_cancel) {
3128
                // Task is cancelled right before coro stops.
3129
0
                task->task_must_cancel = 0;
3130
0
                tmp = future_cancel(state, (FutureObj*)task,
3131
0
                                    task->task_cancel_msg);
3132
0
            }
3133
0
            else {
3134
0
                tmp = future_set_result(state, (FutureObj*)task, result);
3135
0
            }
3136
3137
0
            Py_DECREF(result);
3138
3139
0
            if (tmp == NULL) {
3140
0
                return NULL;
3141
0
            }
3142
0
            Py_DECREF(tmp);
3143
0
            Py_RETURN_NONE;
3144
0
        }
3145
3146
0
        if (PyErr_ExceptionMatches(state->asyncio_CancelledError)) {
3147
            /* CancelledError */
3148
3149
0
            PyObject *exc = PyErr_GetRaisedException();
3150
0
            assert(exc);
3151
3152
0
            FutureObj *fut = (FutureObj*)task;
3153
            /* transfer ownership */
3154
0
            fut->fut_cancelled_exc = exc;
3155
3156
0
            return future_cancel(state, fut, NULL);
3157
0
        }
3158
3159
        /* Some other exception; pop it and call Task.set_exception() */
3160
0
        PyObject *exc = PyErr_GetRaisedException();
3161
0
        assert(exc);
3162
3163
0
        o = future_set_exception(state, (FutureObj*)task, exc);
3164
0
        if (!o) {
3165
            /* An exception in Task.set_exception() */
3166
0
            Py_DECREF(exc);
3167
0
            goto fail;
3168
0
        }
3169
0
        assert(o == Py_None);
3170
0
        Py_DECREF(o);
3171
3172
0
        if (PyErr_GivenExceptionMatches(exc, PyExc_KeyboardInterrupt) ||
3173
0
            PyErr_GivenExceptionMatches(exc, PyExc_SystemExit))
3174
0
        {
3175
            /* We've got a KeyboardInterrupt or a SystemError; re-raise it */
3176
0
            PyErr_SetRaisedException(exc);
3177
0
            goto fail;
3178
0
        }
3179
3180
0
        Py_DECREF(exc);
3181
3182
0
        Py_RETURN_NONE;
3183
0
    }
3184
3185
0
    PyObject *ret = task_step_handle_result_impl(state, task, result);
3186
0
    return ret;
3187
3188
0
fail:
3189
0
    return NULL;
3190
0
}
3191
3192
3193
static PyObject *
3194
task_step_handle_result_impl(asyncio_state *state, TaskObj *task, PyObject *result)
3195
0
{
3196
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(task);
3197
3198
0
    int res;
3199
0
    PyObject *o;
3200
3201
0
    if (result == (PyObject*)task) {
3202
        /* We have a task that wants to await on itself */
3203
0
        goto self_await;
3204
0
    }
3205
3206
    /* Check if `result` is FutureObj or TaskObj (and not a subclass) */
3207
0
    if (Future_CheckExact(state, result) || Task_CheckExact(state, result)) {
3208
0
        PyObject *wrapper;
3209
0
        PyObject *tmp;
3210
0
        FutureObj *fut = (FutureObj*)result;
3211
3212
        /* Check if `result` future is attached to a different loop */
3213
0
        if (fut->fut_loop != task->task_loop) {
3214
0
            goto different_loop;
3215
0
        }
3216
3217
0
        if (!fut->fut_blocking) {
3218
0
            goto yield_insteadof_yf;
3219
0
        }
3220
0
        int res;
3221
0
        Py_BEGIN_CRITICAL_SECTION(result);
3222
0
        res = future_awaited_by_add(state, (FutureObj *)result, (PyObject *)task);
3223
0
        Py_END_CRITICAL_SECTION();
3224
0
        if (res) {
3225
0
            goto fail;
3226
0
        }
3227
3228
0
        fut->fut_blocking = 0;
3229
3230
        /* result.add_done_callback(task._wakeup) */
3231
0
        wrapper = PyCFunction_New(&TaskWakeupDef, (PyObject *)task);
3232
0
        if (wrapper == NULL) {
3233
0
            goto fail;
3234
0
        }
3235
0
        Py_BEGIN_CRITICAL_SECTION(result);
3236
0
        tmp = future_add_done_callback(state,
3237
0
            (FutureObj*)result, wrapper, task->task_context);
3238
0
        Py_END_CRITICAL_SECTION();
3239
0
        Py_DECREF(wrapper);
3240
0
        if (tmp == NULL) {
3241
0
            goto fail;
3242
0
        }
3243
0
        Py_DECREF(tmp);
3244
3245
        /* task._fut_waiter = result */
3246
0
        task->task_fut_waiter = result;  /* no incref is necessary */
3247
3248
0
        if (task->task_must_cancel) {
3249
0
            PyObject *r;
3250
0
            int is_true;
3251
3252
            // Beware: An evil `__getattribute__` could
3253
            // prematurely delete task->task_cancel_msg before the
3254
            // task is cancelled, thereby causing a UAF crash.
3255
            //
3256
            // See https://github.com/python/cpython/issues/126138
3257
0
            PyObject *task_cancel_msg = Py_NewRef(task->task_cancel_msg);
3258
0
            r = PyObject_CallMethodOneArg(result, &_Py_ID(cancel),
3259
0
                                          task_cancel_msg);
3260
0
            Py_DECREF(task_cancel_msg);
3261
3262
0
            if (r == NULL) {
3263
0
                return NULL;
3264
0
            }
3265
0
            is_true = PyObject_IsTrue(r);
3266
0
            Py_DECREF(r);
3267
0
            if (is_true < 0) {
3268
0
                return NULL;
3269
0
            }
3270
0
            else if (is_true) {
3271
0
                task->task_must_cancel = 0;
3272
0
            }
3273
0
        }
3274
3275
0
        Py_RETURN_NONE;
3276
0
    }
3277
3278
    /* Check if `result` is None */
3279
0
    if (result == Py_None) {
3280
        /* Bare yield relinquishes control for one event loop iteration. */
3281
0
        if (task_call_step_soon(state, task, NULL)) {
3282
0
            goto fail;
3283
0
        }
3284
0
        return result;
3285
0
    }
3286
3287
    /* Check if `result` is a Future-compatible object */
3288
0
    if (PyObject_GetOptionalAttr(result, &_Py_ID(_asyncio_future_blocking), &o) < 0) {
3289
0
        goto fail;
3290
0
    }
3291
0
    if (o != NULL && o != Py_None) {
3292
        /* `result` is a Future-compatible object */
3293
0
        PyObject *wrapper;
3294
0
        PyObject *tmp;
3295
3296
0
        int blocking = PyObject_IsTrue(o);
3297
0
        Py_DECREF(o);
3298
0
        if (blocking < 0) {
3299
0
            goto fail;
3300
0
        }
3301
3302
        /* Check if `result` future is attached to a different loop */
3303
0
        PyObject *oloop = get_future_loop(state, result);
3304
0
        if (oloop == NULL) {
3305
0
            goto fail;
3306
0
        }
3307
0
        if (oloop != task->task_loop) {
3308
0
            Py_DECREF(oloop);
3309
0
            goto different_loop;
3310
0
        }
3311
0
        Py_DECREF(oloop);
3312
3313
0
        if (!blocking) {
3314
0
            goto yield_insteadof_yf;
3315
0
        }
3316
3317
0
        if (TaskOrFuture_Check(state, result)) {
3318
0
            int res;
3319
0
            Py_BEGIN_CRITICAL_SECTION(result);
3320
0
            res = future_awaited_by_add(state, (FutureObj *)result, (PyObject *)task);
3321
0
            Py_END_CRITICAL_SECTION();
3322
0
            if (res) {
3323
0
                goto fail;
3324
0
            }
3325
0
        }
3326
3327
        /* result._asyncio_future_blocking = False */
3328
0
        if (PyObject_SetAttr(
3329
0
                result, &_Py_ID(_asyncio_future_blocking), Py_False) == -1) {
3330
0
            goto fail;
3331
0
        }
3332
3333
0
        wrapper = PyCFunction_New(&TaskWakeupDef, (PyObject *)task);
3334
0
        if (wrapper == NULL) {
3335
0
            goto fail;
3336
0
        }
3337
3338
        /* result.add_done_callback(task._wakeup) */
3339
0
        PyObject *add_cb = PyObject_GetAttr(
3340
0
            result, &_Py_ID(add_done_callback));
3341
0
        if (add_cb == NULL) {
3342
0
            Py_DECREF(wrapper);
3343
0
            goto fail;
3344
0
        }
3345
0
        PyObject *stack[2];
3346
0
        stack[0] = wrapper;
3347
0
        stack[1] = (PyObject *)task->task_context;
3348
0
        EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, add_cb);
3349
0
        tmp = PyObject_Vectorcall(add_cb, stack, 1, state->context_kwname);
3350
0
        Py_DECREF(add_cb);
3351
0
        Py_DECREF(wrapper);
3352
0
        if (tmp == NULL) {
3353
0
            goto fail;
3354
0
        }
3355
0
        Py_DECREF(tmp);
3356
3357
        /* task._fut_waiter = result */
3358
0
        task->task_fut_waiter = result;  /* no incref is necessary */
3359
3360
0
        if (task->task_must_cancel) {
3361
0
            PyObject *r;
3362
0
            int is_true;
3363
3364
            // Beware: An evil `__getattribute__` could
3365
            // prematurely delete task->task_cancel_msg before the
3366
            // task is cancelled, thereby causing a UAF crash.
3367
            //
3368
            // See https://github.com/python/cpython/issues/126138
3369
0
            PyObject *task_cancel_msg = Py_NewRef(task->task_cancel_msg);
3370
0
            r = PyObject_CallMethodOneArg(result, &_Py_ID(cancel),
3371
0
                                          task_cancel_msg);
3372
0
            Py_DECREF(task_cancel_msg);
3373
3374
0
            if (r == NULL) {
3375
0
                return NULL;
3376
0
            }
3377
0
            is_true = PyObject_IsTrue(r);
3378
0
            Py_DECREF(r);
3379
0
            if (is_true < 0) {
3380
0
                return NULL;
3381
0
            }
3382
0
            else if (is_true) {
3383
0
                task->task_must_cancel = 0;
3384
0
            }
3385
0
        }
3386
3387
0
        Py_RETURN_NONE;
3388
0
    }
3389
3390
0
    Py_XDECREF(o);
3391
    /* Check if `result` is a generator */
3392
0
    res = PyObject_IsInstance(result, (PyObject*)&PyGen_Type);
3393
0
    if (res < 0) {
3394
0
        goto fail;
3395
0
    }
3396
0
    if (res) {
3397
        /* `result` is a generator */
3398
0
        o = task_set_error_soon(
3399
0
            state, task, PyExc_RuntimeError,
3400
0
            "yield was used instead of yield from for "
3401
0
            "generator in task %R with %R", task, result);
3402
0
        Py_DECREF(result);
3403
0
        return o;
3404
0
    }
3405
3406
    /* The `result` is none of the above */
3407
0
    o = task_set_error_soon(
3408
0
        state, task, PyExc_RuntimeError, "Task got bad yield: %R", result);
3409
0
    Py_DECREF(result);
3410
0
    return o;
3411
3412
0
self_await:
3413
0
    o = task_set_error_soon(
3414
0
        state, task, PyExc_RuntimeError,
3415
0
        "Task cannot await on itself: %R", task);
3416
0
    Py_DECREF(result);
3417
0
    return o;
3418
3419
0
yield_insteadof_yf:
3420
0
    o = task_set_error_soon(
3421
0
        state, task, PyExc_RuntimeError,
3422
0
        "yield was used instead of yield from "
3423
0
        "in task %R with %R",
3424
0
        task, result);
3425
0
    Py_DECREF(result);
3426
0
    return o;
3427
3428
0
different_loop:
3429
0
    o = task_set_error_soon(
3430
0
        state, task, PyExc_RuntimeError,
3431
0
        "Task %R got Future %R attached to a different loop",
3432
0
        task, result);
3433
0
    Py_DECREF(result);
3434
0
    return o;
3435
3436
0
fail:
3437
0
    Py_XDECREF(result);
3438
0
    return NULL;
3439
0
}
3440
3441
static PyObject *
3442
task_step(asyncio_state *state, TaskObj *task, PyObject *exc)
3443
0
{
3444
0
    PyObject *res;
3445
3446
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3447
3448
0
    if (enter_task(ts, task->task_loop, (PyObject*)task) < 0) {
3449
0
        return NULL;
3450
0
    }
3451
3452
0
    res = task_step_impl(state, task, exc);
3453
3454
0
    if (res == NULL) {
3455
0
        PyObject *exc = PyErr_GetRaisedException();
3456
0
        leave_task(ts, task->task_loop, (PyObject*)task);
3457
0
        _PyErr_ChainExceptions1(exc);
3458
0
        return NULL;
3459
0
    }
3460
0
    else {
3461
0
        if (leave_task(ts, task->task_loop, (PyObject*)task) < 0) {
3462
0
            Py_DECREF(res);
3463
0
            return NULL;
3464
0
        }
3465
0
        else {
3466
0
            return res;
3467
0
        }
3468
0
    }
3469
0
}
3470
3471
static int
3472
task_eager_start(_PyThreadStateImpl *ts, asyncio_state *state, TaskObj *task)
3473
0
{
3474
0
    assert(task != NULL);
3475
0
    PyObject *prevtask = swap_current_task(ts, task->task_loop, (PyObject *)task);
3476
0
    if (prevtask == NULL) {
3477
0
        return -1;
3478
0
    }
3479
    // register the task into the linked list of tasks
3480
    // if the task completes eagerly (without suspending) then it will unregister itself
3481
    // in future_schedule_callbacks when done, otherwise
3482
    // it will continue as a regular (non-eager) asyncio task
3483
0
    register_task(ts, task);
3484
3485
0
    assert(PyContext_CheckExact(task->task_context));
3486
0
    if (_PyContext_Enter(&ts->base, task->task_context) == -1) {
3487
        // gh-157301: a failed enter must not leave the task current and registered
3488
0
        task->task_log_destroy_pending = 0;
3489
0
        PyObject *curtask = swap_current_task(ts, task->task_loop, prevtask);
3490
0
        Py_XDECREF(curtask);
3491
0
        unregister_task(task);
3492
0
        Py_DECREF(prevtask);
3493
0
        return -1;
3494
0
    }
3495
3496
0
    int retval = 0;
3497
3498
    // gh-157299: the eager step must record the awaited_by edge
3499
0
    int eager_edge = TaskOrFuture_Check(state, prevtask);
3500
0
    PyObject *stepres;
3501
0
    Py_BEGIN_CRITICAL_SECTION(task);
3502
0
    if (eager_edge &&
3503
0
        future_awaited_by_add(state, (FutureObj *)task, prevtask) < 0)
3504
0
    {
3505
0
        eager_edge = 0;
3506
0
        task->task_log_destroy_pending = 0;
3507
0
        unregister_task(task);
3508
0
        stepres = NULL;
3509
0
    }
3510
0
    else {
3511
0
        stepres = task_step_impl(state, task, NULL);
3512
0
    }
3513
3514
0
    PyObject *exc = stepres == NULL ? PyErr_GetRaisedException() : NULL;
3515
0
    if (eager_edge) {
3516
0
        int res = future_awaited_by_discard(state, (FutureObj *)task, prevtask);
3517
0
        if (res) {
3518
0
            retval = -1;
3519
0
        }
3520
0
    }
3521
0
    if (stepres == NULL) {
3522
0
        _PyErr_ChainExceptions1(exc);
3523
0
        retval = -1;
3524
0
    } else {
3525
0
        Py_DECREF(stepres);
3526
0
    }
3527
0
    Py_END_CRITICAL_SECTION();
3528
3529
0
    PyObject *curtask = swap_current_task(ts, task->task_loop, prevtask);
3530
0
    Py_DECREF(prevtask);
3531
0
    if (curtask == NULL) {
3532
0
        retval = -1;
3533
0
    } else {
3534
0
        assert(curtask == (PyObject *)task);
3535
0
        Py_DECREF(curtask);
3536
0
    }
3537
3538
0
    if (_PyContext_Exit(&ts->base, task->task_context) == -1) {
3539
0
        retval = -1;
3540
0
    }
3541
3542
0
    if (task->task_state != STATE_PENDING) {
3543
        // This seems to really help performance on pyperformance benchmarks
3544
0
        clear_task_coro(task);
3545
0
    }
3546
3547
0
    return retval;
3548
0
}
3549
3550
static PyObject *
3551
task_wakeup_lock_held(TaskObj *task, PyObject *o)
3552
0
{
3553
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(task);
3554
3555
0
    PyObject *result;
3556
0
    assert(o);
3557
3558
0
    asyncio_state *state = get_asyncio_state_by_def((PyObject *)task);
3559
3560
0
    if (TaskOrFuture_Check(state, o)) {
3561
0
        int res;
3562
0
        Py_BEGIN_CRITICAL_SECTION(o);
3563
0
        res = future_awaited_by_discard(state, (FutureObj *)o, (PyObject *)task);
3564
0
        Py_END_CRITICAL_SECTION();
3565
0
        if (res) {
3566
0
            return NULL;
3567
0
        }
3568
0
    }
3569
3570
0
    if (Future_CheckExact(state, o) || Task_CheckExact(state, o)) {
3571
0
        PyObject *fut_result = NULL;
3572
0
        int res;
3573
0
        Py_BEGIN_CRITICAL_SECTION(o);
3574
0
        res = future_get_result(state, (FutureObj*)o, &fut_result);
3575
0
        Py_END_CRITICAL_SECTION();
3576
0
        switch(res) {
3577
0
        case -1:
3578
0
            assert(fut_result == NULL);
3579
0
            break; /* exception raised */
3580
0
        case 0:
3581
0
            Py_DECREF(fut_result);
3582
0
            return task_step(state, task, NULL);
3583
0
        default:
3584
0
            assert(res == 1);
3585
0
            result = task_step(state, task, fut_result);
3586
0
            Py_DECREF(fut_result);
3587
0
            return result;
3588
0
        }
3589
0
    }
3590
0
    else {
3591
0
        PyObject *fut_result = PyObject_CallMethod(o, "result", NULL);
3592
0
        if (fut_result != NULL) {
3593
0
            Py_DECREF(fut_result);
3594
0
            return task_step(state, task, NULL);
3595
0
        }
3596
        /* exception raised */
3597
0
    }
3598
3599
0
    PyObject *exc = PyErr_GetRaisedException();
3600
0
    assert(exc);
3601
3602
0
    result = task_step(state, task, exc);
3603
3604
0
    Py_DECREF(exc);
3605
3606
0
    return result;
3607
0
}
3608
3609
static PyObject *
3610
task_wakeup(PyObject *op, PyObject *arg)
3611
0
{
3612
0
    TaskObj *task = (TaskObj*)op;
3613
0
    PyObject *res;
3614
0
    Py_BEGIN_CRITICAL_SECTION(task);
3615
0
    res = task_wakeup_lock_held(task, arg);
3616
0
    Py_END_CRITICAL_SECTION();
3617
0
    return res;
3618
0
}
3619
3620
3621
/*********************** Functions **************************/
3622
3623
3624
/*[clinic input]
3625
_asyncio._get_running_loop
3626
3627
Return the running event loop or None.
3628
3629
This is a low-level function intended to be used by event loops.
3630
This function is thread-specific.
3631
3632
[clinic start generated code]*/
3633
3634
static PyObject *
3635
_asyncio__get_running_loop_impl(PyObject *module)
3636
/*[clinic end generated code: output=b4390af721411a0a input=0a21627e25a4bd43]*/
3637
0
{
3638
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3639
0
    PyObject *loop = Py_XNewRef(ts->asyncio_running_loop);
3640
0
    if (loop == NULL) {
3641
        /* There's no currently running event loop */
3642
0
        Py_RETURN_NONE;
3643
0
    }
3644
0
    return loop;
3645
0
}
3646
3647
/*[clinic input]
3648
_asyncio._set_running_loop
3649
    loop: 'O'
3650
    /
3651
3652
Set the running event loop.
3653
3654
This is a low-level function intended to be used by event loops.
3655
This function is thread-specific.
3656
[clinic start generated code]*/
3657
3658
static PyObject *
3659
_asyncio__set_running_loop(PyObject *module, PyObject *loop)
3660
/*[clinic end generated code: output=ae56bf7a28ca189a input=4c9720233d606604]*/
3661
0
{
3662
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3663
0
    if (loop == Py_None) {
3664
0
        loop = NULL;
3665
0
    }
3666
0
    Py_XSETREF(ts->asyncio_running_loop, Py_XNewRef(loop));
3667
0
    Py_RETURN_NONE;
3668
0
}
3669
3670
/*[clinic input]
3671
_asyncio.get_event_loop
3672
3673
Return an asyncio event loop.
3674
3675
When called from a coroutine or a callback (e.g. scheduled with
3676
call_soon or similar API), this function will always return the
3677
running event loop.
3678
3679
If there is no running event loop set, the function will return
3680
the loop set by `set_event_loop()`, or raise a RuntimeError if
3681
no loop has been set.
3682
[clinic start generated code]*/
3683
3684
static PyObject *
3685
_asyncio_get_event_loop_impl(PyObject *module)
3686
/*[clinic end generated code: output=2a2d8b2f824c648b input=fa104f00dc7995dc]*/
3687
0
{
3688
0
    asyncio_state *state = get_asyncio_state(module);
3689
0
    return get_event_loop(state);
3690
0
}
3691
3692
/*[clinic input]
3693
_asyncio.get_running_loop
3694
3695
Return the running event loop.  Raise a RuntimeError if there is none.
3696
3697
This function is thread-specific.
3698
[clinic start generated code]*/
3699
3700
static PyObject *
3701
_asyncio_get_running_loop_impl(PyObject *module)
3702
/*[clinic end generated code: output=c247b5f9e529530e input=2a3bf02ba39f173d]*/
3703
0
{
3704
0
    PyObject *loop;
3705
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3706
0
    loop = Py_XNewRef(ts->asyncio_running_loop);
3707
0
    if (loop == NULL) {
3708
        /* There's no currently running event loop */
3709
0
        PyErr_SetString(
3710
0
            PyExc_RuntimeError, "no running event loop");
3711
0
        return NULL;
3712
0
    }
3713
0
    return loop;
3714
0
}
3715
3716
/*[clinic input]
3717
_asyncio._register_task
3718
3719
    task: object
3720
3721
Register a new task in asyncio as executed by loop.
3722
3723
Returns None.
3724
[clinic start generated code]*/
3725
3726
static PyObject *
3727
_asyncio__register_task_impl(PyObject *module, PyObject *task)
3728
/*[clinic end generated code: output=8672dadd69a7d4e2 input=21075aaea14dfbad]*/
3729
0
{
3730
0
    asyncio_state *state = get_asyncio_state(module);
3731
0
    if (Task_Check(state, task)) {
3732
        // task is an asyncio.Task instance or subclass, use efficient
3733
        // linked-list implementation.
3734
0
        _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3735
0
        register_task(ts, (TaskObj *)task);
3736
0
        Py_RETURN_NONE;
3737
0
    }
3738
    // As task does not inherit from asyncio.Task, fallback to less efficient
3739
    // weakset implementation.
3740
0
    PyObject *res = PyObject_CallMethodOneArg(state->non_asyncio_tasks,
3741
0
                                              &_Py_ID(add), task);
3742
0
    if (res == NULL) {
3743
0
        return NULL;
3744
0
    }
3745
0
    Py_DECREF(res);
3746
0
    Py_RETURN_NONE;
3747
0
}
3748
3749
/*[clinic input]
3750
_asyncio._register_eager_task
3751
3752
    task: object
3753
3754
Register a new task in asyncio as executed by loop.
3755
3756
Returns None.
3757
[clinic start generated code]*/
3758
3759
static PyObject *
3760
_asyncio__register_eager_task_impl(PyObject *module, PyObject *task)
3761
/*[clinic end generated code: output=dfe1d45367c73f1a input=237f684683398c51]*/
3762
0
{
3763
0
    asyncio_state *state = get_asyncio_state(module);
3764
3765
0
    if (Task_Check(state, task)) {
3766
        // task is an asyncio.Task instance or subclass, use efficient
3767
        // linked-list implementation.
3768
0
        _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3769
0
        register_task(ts, (TaskObj *)task);
3770
0
        Py_RETURN_NONE;
3771
0
    }
3772
3773
0
    if (PySet_Add(state->non_asyncio_eager_tasks, task) < 0) {
3774
0
        return NULL;
3775
0
    }
3776
3777
0
    Py_RETURN_NONE;
3778
0
}
3779
3780
3781
/*[clinic input]
3782
_asyncio._unregister_task
3783
3784
    task: object
3785
3786
Unregister a task.
3787
3788
Returns None.
3789
[clinic start generated code]*/
3790
3791
static PyObject *
3792
_asyncio__unregister_task_impl(PyObject *module, PyObject *task)
3793
/*[clinic end generated code: output=6e5585706d568a46 input=28fb98c3975f7bdc]*/
3794
0
{
3795
0
    asyncio_state *state = get_asyncio_state(module);
3796
0
    if (Task_Check(state, task)) {
3797
0
        unregister_task((TaskObj *)task);
3798
0
        Py_RETURN_NONE;
3799
0
    }
3800
0
    PyObject *res = PyObject_CallMethodOneArg(state->non_asyncio_tasks,
3801
0
                                              &_Py_ID(discard), task);
3802
0
    if (res == NULL) {
3803
0
        return NULL;
3804
0
    }
3805
0
    Py_DECREF(res);
3806
0
    Py_RETURN_NONE;
3807
0
}
3808
3809
/*[clinic input]
3810
_asyncio._unregister_eager_task
3811
3812
    task: object
3813
3814
Unregister a task.
3815
3816
Returns None.
3817
[clinic start generated code]*/
3818
3819
static PyObject *
3820
_asyncio__unregister_eager_task_impl(PyObject *module, PyObject *task)
3821
/*[clinic end generated code: output=a426922bd07f23d1 input=9d07401ef14ee048]*/
3822
0
{
3823
0
    asyncio_state *state = get_asyncio_state(module);
3824
0
    if (Task_Check(state, task)) {
3825
        // task is an asyncio.Task instance or subclass, use efficient
3826
        // linked-list implementation.
3827
0
        unregister_task((TaskObj *)task);
3828
0
        Py_RETURN_NONE;
3829
0
    }
3830
3831
0
    if (PySet_Discard(state->non_asyncio_eager_tasks, task) < 0) {
3832
0
        return NULL;
3833
0
    }
3834
3835
0
    Py_RETURN_NONE;
3836
0
}
3837
3838
3839
/*[clinic input]
3840
_asyncio._enter_task
3841
3842
    loop: object
3843
    task: object
3844
3845
Enter into task execution or resume suspended task.
3846
3847
Task belongs to loop.
3848
3849
Returns None.
3850
[clinic start generated code]*/
3851
3852
static PyObject *
3853
_asyncio__enter_task_impl(PyObject *module, PyObject *loop, PyObject *task)
3854
/*[clinic end generated code: output=a22611c858035b73 input=de1b06dca70d8737]*/
3855
0
{
3856
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3857
0
    if (enter_task(ts, loop, task) < 0) {
3858
0
        return NULL;
3859
0
    }
3860
0
    Py_RETURN_NONE;
3861
0
}
3862
3863
3864
/*[clinic input]
3865
_asyncio._leave_task
3866
3867
    loop: object
3868
    task: object
3869
3870
Leave task execution or suspend a task.
3871
3872
Task belongs to loop.
3873
3874
Returns None.
3875
[clinic start generated code]*/
3876
3877
static PyObject *
3878
_asyncio__leave_task_impl(PyObject *module, PyObject *loop, PyObject *task)
3879
/*[clinic end generated code: output=0ebf6db4b858fb41 input=51296a46313d1ad8]*/
3880
0
{
3881
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3882
0
    if (leave_task(ts, loop, task) < 0) {
3883
0
        return NULL;
3884
0
    }
3885
0
    Py_RETURN_NONE;
3886
0
}
3887
3888
3889
/*[clinic input]
3890
@permit_long_summary
3891
_asyncio._swap_current_task
3892
3893
    loop: object
3894
    task: object
3895
3896
Temporarily swap in the supplied task and return the original one (or None).
3897
3898
This is intended for use during eager coroutine execution.
3899
3900
[clinic start generated code]*/
3901
3902
static PyObject *
3903
_asyncio__swap_current_task_impl(PyObject *module, PyObject *loop,
3904
                                 PyObject *task)
3905
/*[clinic end generated code: output=9f88de958df74c7e input=ec14ed25855e3068]*/
3906
0
{
3907
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3908
0
    return swap_current_task(ts, loop, task);
3909
0
}
3910
3911
3912
/*[clinic input]
3913
_asyncio.current_task
3914
3915
    loop: object = None
3916
3917
Return a currently executed task.
3918
3919
[clinic start generated code]*/
3920
3921
static PyObject *
3922
_asyncio_current_task_impl(PyObject *module, PyObject *loop)
3923
/*[clinic end generated code: output=fe15ac331a7f981a input=58910f61a5627112]*/
3924
0
{
3925
0
    if (loop == Py_None) {
3926
0
        loop = _asyncio_get_running_loop_impl(module);
3927
0
        if (loop == NULL) {
3928
0
            return NULL;
3929
0
        }
3930
0
    } else {
3931
0
        Py_INCREF(loop);
3932
0
    }
3933
3934
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
3935
    // Fast path for the current running loop of current thread
3936
    // no locking or stop the world pause is required
3937
0
    if (ts->asyncio_running_loop == loop) {
3938
0
        if (ts->asyncio_running_task != NULL) {
3939
0
            Py_DECREF(loop);
3940
0
            return Py_NewRef(ts->asyncio_running_task);
3941
0
        }
3942
0
        Py_DECREF(loop);
3943
0
        Py_RETURN_NONE;
3944
0
    }
3945
3946
0
    PyObject *ret = Py_None;
3947
    // Stop the world and traverse the per-thread current tasks
3948
    // and return the task if the loop matches
3949
0
    PyInterpreterState *interp = ts->base.interp;
3950
0
    _PyEval_StopTheWorld(interp);
3951
0
    _Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
3952
0
        ts = (_PyThreadStateImpl *)p;
3953
0
        if (ts->asyncio_running_loop == loop) {
3954
0
            if (ts->asyncio_running_task != NULL) {
3955
0
                ret = Py_NewRef(ts->asyncio_running_task);
3956
0
            }
3957
0
            goto exit;
3958
0
        }
3959
0
    }
3960
0
exit:
3961
0
    _Py_FOR_EACH_TSTATE_END(interp);
3962
0
    _PyEval_StartTheWorld(interp);
3963
0
    Py_DECREF(loop);
3964
0
    return ret;
3965
0
}
3966
3967
3968
static inline int
3969
add_one_task(asyncio_state *state, PyObject *tasks, PyObject *task, PyObject *loop)
3970
0
{
3971
0
    assert(PySet_CheckExact(tasks));
3972
0
    if (Task_CheckExact(state, task)) {
3973
0
        int pending = 0;
3974
0
        Py_BEGIN_CRITICAL_SECTION(task);
3975
0
        pending = ((TaskObj *)task)->task_state == STATE_PENDING && ((TaskObj *)task)->task_loop == loop;
3976
0
        Py_END_CRITICAL_SECTION();
3977
0
        if (pending) {
3978
0
            if (PySet_Add(tasks, task) < 0) {
3979
0
                return -1;
3980
0
            }
3981
0
        }
3982
0
        return 0;
3983
0
    }
3984
3985
0
    PyObject *done = PyObject_CallMethodNoArgs(task, &_Py_ID(done));
3986
0
    if (done == NULL) {
3987
0
        return -1;
3988
0
    }
3989
0
    if (Py_IsTrue(done)) {
3990
0
        return 0;
3991
0
    }
3992
0
    Py_DECREF(done);
3993
0
    PyObject *task_loop = get_future_loop(state, task);
3994
0
    if (task_loop == NULL) {
3995
0
        return -1;
3996
0
    }
3997
0
    if (task_loop == loop) {
3998
0
        if (PySet_Add(tasks, task) < 0) {
3999
0
            Py_DECREF(task_loop);
4000
0
            return -1;
4001
0
        }
4002
0
    }
4003
0
    Py_DECREF(task_loop);
4004
0
    return 0;
4005
0
}
4006
4007
static inline int
4008
add_tasks_llist(struct llist_node *head, PyListObject *tasks)
4009
0
{
4010
0
    struct llist_node *node;
4011
0
    llist_for_each_safe(node, head) {
4012
0
        TaskObj *task = llist_data(node, TaskObj, task_node);
4013
        // The linked list holds borrowed references to task
4014
        // as such it is possible that the task is concurrently
4015
        // deallocated while added to this list.
4016
        // To protect against concurrent deallocations,
4017
        // we first try to incref the task which would fail
4018
        // if it is concurrently getting deallocated in another thread,
4019
        // otherwise it gets added to the list.
4020
0
        if (_Py_TryIncref((PyObject *)task)) {
4021
0
            if (_PyList_AppendTakeRef(tasks, (PyObject *)task) < 0) {
4022
                // do not call any escaping calls here while the world is stopped.
4023
0
                return -1;
4024
0
            }
4025
0
        }
4026
0
    }
4027
0
    return 0;
4028
0
}
4029
4030
static inline int
4031
add_tasks_interp(PyInterpreterState *interp, PyListObject *tasks)
4032
0
{
4033
#ifdef Py_GIL_DISABLED
4034
    assert(interp->stoptheworld.world_stopped);
4035
#endif
4036
    // Start traversing from interpreter's linked list
4037
0
    struct llist_node *head = &interp->asyncio_tasks_head;
4038
4039
0
    if (add_tasks_llist(head, tasks) < 0) {
4040
0
        return -1;
4041
0
    }
4042
4043
0
    int ret = 0;
4044
    // traverse the task lists of thread states
4045
0
    _Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
4046
0
        _PyThreadStateImpl *ts = (_PyThreadStateImpl *)p;
4047
0
        head = &ts->asyncio_tasks_head;
4048
0
        if (add_tasks_llist(head, tasks) < 0) {
4049
0
            ret = -1;
4050
0
            goto exit;
4051
0
        }
4052
0
    }
4053
0
exit:
4054
0
    _Py_FOR_EACH_TSTATE_END(interp);
4055
0
    return ret;
4056
0
}
4057
4058
/*********************** Module **************************/
4059
4060
/*[clinic input]
4061
_asyncio.all_tasks
4062
4063
    loop: object = None
4064
4065
Return a set of all tasks for the loop.
4066
4067
[clinic start generated code]*/
4068
4069
static PyObject *
4070
_asyncio_all_tasks_impl(PyObject *module, PyObject *loop)
4071
/*[clinic end generated code: output=0e107cbb7f72aa7b input=43a1b423c2d95bfa]*/
4072
0
{
4073
0
    asyncio_state *state = get_asyncio_state(module);
4074
0
    if (loop == Py_None) {
4075
0
        loop = _asyncio_get_running_loop_impl(module);
4076
0
        if (loop == NULL) {
4077
0
            return NULL;
4078
0
        }
4079
0
    } else {
4080
0
        Py_INCREF(loop);
4081
0
    }
4082
    // First add eager tasks to the list so that we don't miss
4083
    // any tasks which graduates from eager to non-eager
4084
    // We first add all the tasks to `tasks` list and then filter
4085
    // out the tasks which are done and return it as a set.
4086
0
    PyObject *tasks = PyList_New(0);
4087
0
    if (tasks == NULL) {
4088
0
        Py_DECREF(loop);
4089
0
        return NULL;
4090
0
    }
4091
0
    if (PyList_Extend(tasks, state->non_asyncio_eager_tasks) < 0) {
4092
0
        Py_DECREF(tasks);
4093
0
        Py_DECREF(loop);
4094
0
        return NULL;
4095
0
    }
4096
0
    if (PyList_Extend(tasks, state->non_asyncio_tasks) < 0) {
4097
0
        Py_DECREF(tasks);
4098
0
        Py_DECREF(loop);
4099
0
        return NULL;
4100
0
    }
4101
4102
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
4103
0
    if (ts->asyncio_running_loop == loop) {
4104
        // Fast path for the current running loop of current thread
4105
        // no locking or stop the world pause is required
4106
0
        struct llist_node *head = &ts->asyncio_tasks_head;
4107
0
        if (add_tasks_llist(head, (PyListObject *)tasks) < 0) {
4108
0
            Py_DECREF(tasks);
4109
0
            Py_DECREF(loop);
4110
0
            return NULL;
4111
0
        }
4112
0
    }
4113
0
    else {
4114
        // Slow path for loop running in different thread
4115
0
        PyInterpreterState *interp = ts->base.interp;
4116
        // Stop the world and traverse the per-thread linked list
4117
        // of asyncio tasks for every thread, as well as the
4118
        // interpreter's linked list, and add them to `tasks`.
4119
        // The interpreter linked list is used for any lingering tasks
4120
        // whose thread state has been deallocated while the task was
4121
        // still alive. This can happen if a task is referenced by
4122
        // a different thread, in which case the task is moved to
4123
        // the interpreter's linked list from the thread's linked
4124
        // list before deallocation. See PyThreadState_Clear.
4125
        //
4126
        // The stop-the-world pause is required so that no thread
4127
        // modifies its linked list while being iterated here
4128
        // in parallel. This design allows for lock-free
4129
        // register_task/unregister_task for loops running in parallel
4130
        // in different threads (the general case).
4131
0
        _PyEval_StopTheWorld(interp);
4132
0
        int ret = add_tasks_interp(interp, (PyListObject *)tasks);
4133
0
        _PyEval_StartTheWorld(interp);
4134
0
        if (ret < 0) {
4135
            // call any escaping calls after starting the world to avoid any deadlocks.
4136
0
            Py_DECREF(tasks);
4137
0
            Py_DECREF(loop);
4138
0
            return NULL;
4139
0
        }
4140
0
    }
4141
4142
    // All the tasks are now in the list, now filter the tasks which are done
4143
0
    PyObject *res = PySet_New(NULL);
4144
0
    if (res == NULL) {
4145
0
        Py_DECREF(tasks);
4146
0
        Py_DECREF(loop);
4147
0
        return NULL;
4148
0
    }
4149
4150
0
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(tasks); i++) {
4151
0
        PyObject *task = PyList_GET_ITEM(tasks, i);
4152
0
        if (add_one_task(state, res, task, loop) < 0) {
4153
0
            Py_DECREF(res);
4154
0
            Py_DECREF(tasks);
4155
0
            Py_DECREF(loop);
4156
0
            return NULL;
4157
0
        }
4158
0
    }
4159
4160
0
    Py_DECREF(tasks);
4161
0
    Py_DECREF(loop);
4162
0
    return res;
4163
0
}
4164
4165
/*[clinic input]
4166
_asyncio.future_add_to_awaited_by
4167
4168
    fut: object
4169
    waiter: object
4170
    /
4171
4172
Record that `fut` is awaited on by `waiter`.
4173
4174
[clinic start generated code]*/
4175
4176
static PyObject *
4177
_asyncio_future_add_to_awaited_by_impl(PyObject *module, PyObject *fut,
4178
                                       PyObject *waiter)
4179
/*[clinic end generated code: output=0ab9a1a63389e4df input=06e6eaac51f532b9]*/
4180
0
{
4181
0
    asyncio_state *state = get_asyncio_state(module);
4182
0
    if (TaskOrFuture_Check(state, fut) && TaskOrFuture_Check(state, waiter)) {
4183
0
        int res;
4184
0
        Py_BEGIN_CRITICAL_SECTION(fut);
4185
0
        res = future_awaited_by_add(state, (FutureObj *)fut, waiter);
4186
0
        Py_END_CRITICAL_SECTION();
4187
0
        if (res) {
4188
0
            return NULL;
4189
0
        }
4190
0
    }
4191
0
    Py_RETURN_NONE;
4192
0
}
4193
4194
/*[clinic input]
4195
_asyncio.future_discard_from_awaited_by
4196
4197
    fut: object
4198
    waiter: object
4199
    /
4200
4201
[clinic start generated code]*/
4202
4203
static PyObject *
4204
_asyncio_future_discard_from_awaited_by_impl(PyObject *module, PyObject *fut,
4205
                                             PyObject *waiter)
4206
/*[clinic end generated code: output=a03b0b4323b779de input=3833f7639e88e483]*/
4207
0
{
4208
0
    asyncio_state *state = get_asyncio_state(module);
4209
0
    if (TaskOrFuture_Check(state, fut) && TaskOrFuture_Check(state, waiter)) {
4210
0
        int res;
4211
0
        Py_BEGIN_CRITICAL_SECTION(fut);
4212
0
        res = future_awaited_by_discard(state, (FutureObj *)fut, waiter);
4213
0
        Py_END_CRITICAL_SECTION();
4214
0
        if (res) {
4215
0
            return NULL;
4216
0
        }
4217
0
    }
4218
0
    Py_RETURN_NONE;
4219
0
}
4220
4221
/*[clinic input]
4222
_asyncio._clear_caches
4223
4224
Clear internal caches. Used for internal tests.
4225
[clinic start generated code]*/
4226
4227
static PyObject *
4228
_asyncio__clear_caches_impl(PyObject *module)
4229
/*[clinic end generated code: output=9691a293f83d4303 input=6e1ae31e51dc906c]*/
4230
0
{
4231
0
    asyncio_state *state = get_asyncio_state(module);
4232
0
    if (PySet_Clear(state->iscoroutine_typecache) < 0) {
4233
0
        return NULL;
4234
0
    }
4235
0
    Py_RETURN_NONE;
4236
0
}
4237
4238
static int
4239
module_traverse(PyObject *mod, visitproc visit, void *arg)
4240
0
{
4241
0
    asyncio_state *state = get_asyncio_state(mod);
4242
4243
0
    Py_VISIT(state->FutureIterType);
4244
0
    Py_VISIT(state->TaskStepMethWrapper_Type);
4245
0
    Py_VISIT(state->FutureType);
4246
0
    Py_VISIT(state->TaskType);
4247
4248
0
    Py_VISIT(state->asyncio_mod);
4249
0
    Py_VISIT(state->traceback_extract_stack);
4250
0
    Py_VISIT(state->asyncio_future_repr_func);
4251
0
    Py_VISIT(state->asyncio_get_event_loop);
4252
0
    Py_VISIT(state->asyncio_iscoroutine_func);
4253
0
    Py_VISIT(state->asyncio_task_get_stack_func);
4254
0
    Py_VISIT(state->asyncio_task_print_stack_func);
4255
0
    Py_VISIT(state->asyncio_task_repr_func);
4256
0
    Py_VISIT(state->asyncio_InvalidStateError);
4257
0
    Py_VISIT(state->asyncio_CancelledError);
4258
4259
0
    Py_VISIT(state->non_asyncio_tasks);
4260
0
    Py_VISIT(state->non_asyncio_eager_tasks);
4261
0
    Py_VISIT(state->iscoroutine_typecache);
4262
4263
0
    Py_VISIT(state->context_kwname);
4264
4265
0
    return 0;
4266
0
}
4267
4268
static int
4269
module_clear(PyObject *mod)
4270
0
{
4271
0
    asyncio_state *state = get_asyncio_state(mod);
4272
4273
0
    Py_CLEAR(state->FutureIterType);
4274
0
    Py_CLEAR(state->TaskStepMethWrapper_Type);
4275
0
    Py_CLEAR(state->FutureType);
4276
0
    Py_CLEAR(state->TaskType);
4277
4278
0
    Py_CLEAR(state->asyncio_mod);
4279
0
    Py_CLEAR(state->traceback_extract_stack);
4280
0
    Py_CLEAR(state->asyncio_future_repr_func);
4281
0
    Py_CLEAR(state->asyncio_get_event_loop);
4282
0
    Py_CLEAR(state->asyncio_iscoroutine_func);
4283
0
    Py_CLEAR(state->asyncio_task_get_stack_func);
4284
0
    Py_CLEAR(state->asyncio_task_print_stack_func);
4285
0
    Py_CLEAR(state->asyncio_task_repr_func);
4286
0
    Py_CLEAR(state->asyncio_InvalidStateError);
4287
0
    Py_CLEAR(state->asyncio_CancelledError);
4288
4289
0
    Py_CLEAR(state->non_asyncio_tasks);
4290
0
    Py_CLEAR(state->non_asyncio_eager_tasks);
4291
0
    Py_CLEAR(state->iscoroutine_typecache);
4292
4293
0
    Py_CLEAR(state->context_kwname);
4294
    // Clear the ref to running loop so that finalizers can run early.
4295
    // If there are other running loops in different threads,
4296
    // those get cleared in PyThreadState_Clear.
4297
0
    _PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
4298
0
    Py_CLEAR(ts->asyncio_running_loop);
4299
0
    Py_CLEAR(ts->asyncio_running_task);
4300
4301
0
    return 0;
4302
0
}
4303
4304
static void
4305
module_free(void *mod)
4306
0
{
4307
0
    (void)module_clear((PyObject *)mod);
4308
0
}
4309
4310
static int
4311
module_init(asyncio_state *state)
4312
0
{
4313
0
    PyObject *module = NULL;
4314
4315
0
    state->asyncio_mod = PyImport_ImportModule("asyncio");
4316
0
    if (state->asyncio_mod == NULL) {
4317
0
        goto fail;
4318
0
    }
4319
4320
0
    state->iscoroutine_typecache = PySet_New(NULL);
4321
0
    if (state->iscoroutine_typecache == NULL) {
4322
0
        goto fail;
4323
0
    }
4324
4325
0
    state->context_kwname = Py_BuildValue("(s)", "context");
4326
0
    if (state->context_kwname == NULL) {
4327
0
        goto fail;
4328
0
    }
4329
4330
0
#define WITH_MOD(NAME) \
4331
0
    Py_CLEAR(module); \
4332
0
    module = PyImport_ImportModule(NAME); \
4333
0
    if (module == NULL) { \
4334
0
        goto fail; \
4335
0
    }
4336
4337
0
#define GET_MOD_ATTR(VAR, NAME) \
4338
0
    VAR = PyObject_GetAttrString(module, NAME); \
4339
0
    if (VAR == NULL) { \
4340
0
        goto fail; \
4341
0
    }
4342
4343
0
    WITH_MOD("asyncio.events")
4344
0
    GET_MOD_ATTR(state->asyncio_get_event_loop, "_get_event_loop")
4345
4346
0
    WITH_MOD("asyncio.base_futures")
4347
0
    GET_MOD_ATTR(state->asyncio_future_repr_func, "_future_repr")
4348
4349
0
    WITH_MOD("asyncio.exceptions")
4350
0
    GET_MOD_ATTR(state->asyncio_InvalidStateError, "InvalidStateError")
4351
0
    GET_MOD_ATTR(state->asyncio_CancelledError, "CancelledError")
4352
4353
0
    WITH_MOD("asyncio.base_tasks")
4354
0
    GET_MOD_ATTR(state->asyncio_task_repr_func, "_task_repr")
4355
0
    GET_MOD_ATTR(state->asyncio_task_get_stack_func, "_task_get_stack")
4356
0
    GET_MOD_ATTR(state->asyncio_task_print_stack_func, "_task_print_stack")
4357
4358
0
    WITH_MOD("asyncio.coroutines")
4359
0
    GET_MOD_ATTR(state->asyncio_iscoroutine_func, "iscoroutine")
4360
4361
0
    WITH_MOD("traceback")
4362
0
    GET_MOD_ATTR(state->traceback_extract_stack, "extract_stack")
4363
4364
0
    PyObject *weak_set;
4365
0
    WITH_MOD("weakref")
4366
0
    GET_MOD_ATTR(weak_set, "WeakSet");
4367
0
    state->non_asyncio_tasks = PyObject_CallNoArgs(weak_set);
4368
0
    Py_CLEAR(weak_set);
4369
0
    if (state->non_asyncio_tasks == NULL) {
4370
0
        goto fail;
4371
0
    }
4372
4373
0
    state->non_asyncio_eager_tasks = PySet_New(NULL);
4374
0
    if (state->non_asyncio_eager_tasks == NULL) {
4375
0
        goto fail;
4376
0
    }
4377
4378
0
    state->debug_offsets = &_Py_AsyncioDebug;
4379
4380
0
    Py_DECREF(module);
4381
0
    return 0;
4382
4383
0
fail:
4384
0
    Py_CLEAR(module);
4385
0
    return -1;
4386
4387
0
#undef WITH_MOD
4388
0
#undef GET_MOD_ATTR
4389
0
}
4390
4391
PyDoc_STRVAR(module_doc, "Accelerator module for asyncio");
4392
4393
static PyMethodDef asyncio_methods[] = {
4394
    _ASYNCIO_CURRENT_TASK_METHODDEF
4395
    _ASYNCIO_GET_EVENT_LOOP_METHODDEF
4396
    _ASYNCIO_GET_RUNNING_LOOP_METHODDEF
4397
    _ASYNCIO__GET_RUNNING_LOOP_METHODDEF
4398
    _ASYNCIO__SET_RUNNING_LOOP_METHODDEF
4399
    _ASYNCIO__REGISTER_TASK_METHODDEF
4400
    _ASYNCIO__REGISTER_EAGER_TASK_METHODDEF
4401
    _ASYNCIO__UNREGISTER_TASK_METHODDEF
4402
    _ASYNCIO__UNREGISTER_EAGER_TASK_METHODDEF
4403
    _ASYNCIO__ENTER_TASK_METHODDEF
4404
    _ASYNCIO__LEAVE_TASK_METHODDEF
4405
    _ASYNCIO__SWAP_CURRENT_TASK_METHODDEF
4406
    _ASYNCIO_ALL_TASKS_METHODDEF
4407
    _ASYNCIO_FUTURE_ADD_TO_AWAITED_BY_METHODDEF
4408
    _ASYNCIO_FUTURE_DISCARD_FROM_AWAITED_BY_METHODDEF
4409
    _ASYNCIO__CLEAR_CACHES_METHODDEF
4410
    {NULL, NULL}
4411
};
4412
4413
static int
4414
module_exec(PyObject *mod)
4415
0
{
4416
0
    asyncio_state *state = get_asyncio_state(mod);
4417
4418
4419
0
#define CREATE_TYPE(m, tp, spec, base)                                  \
4420
0
    do {                                                                \
4421
0
        tp = (PyTypeObject *)PyType_FromMetaclass(NULL, m, spec,        \
4422
0
                                                  (PyObject *)base);    \
4423
0
        if (tp == NULL) {                                               \
4424
0
            return -1;                                                  \
4425
0
        }                                                               \
4426
0
    } while (0)
4427
4428
0
    CREATE_TYPE(mod, state->TaskStepMethWrapper_Type, &TaskStepMethWrapper_spec, NULL);
4429
0
    CREATE_TYPE(mod, state->FutureIterType, &FutureIter_spec, NULL);
4430
0
    CREATE_TYPE(mod, state->FutureType, &Future_spec, NULL);
4431
0
    CREATE_TYPE(mod, state->TaskType, &Task_spec, state->FutureType);
4432
4433
0
#undef CREATE_TYPE
4434
4435
0
    if (PyModule_AddType(mod, state->FutureType) < 0) {
4436
0
        return -1;
4437
0
    }
4438
4439
0
    if (PyModule_AddType(mod, state->TaskType) < 0) {
4440
0
        return -1;
4441
0
    }
4442
    // Must be done after types are added to avoid a circular dependency
4443
0
    if (module_init(state) < 0) {
4444
0
        return -1;
4445
0
    }
4446
4447
0
    return 0;
4448
0
}
4449
4450
static struct PyModuleDef_Slot module_slots[] = {
4451
    _Py_ABI_SLOT,
4452
    {Py_mod_exec, module_exec},
4453
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
4454
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
4455
    {0, NULL},
4456
};
4457
4458
static struct PyModuleDef _asynciomodule = {
4459
    .m_base = PyModuleDef_HEAD_INIT,
4460
    .m_name = "_asyncio",
4461
    .m_doc = module_doc,
4462
    .m_size = sizeof(asyncio_state),
4463
    .m_methods = asyncio_methods,
4464
    .m_slots = module_slots,
4465
    .m_traverse = module_traverse,
4466
    .m_clear = module_clear,
4467
    .m_free = module_free,
4468
};
4469
4470
PyMODINIT_FUNC
4471
PyInit__asyncio(void)
4472
0
{
4473
0
    return PyModuleDef_Init(&_asynciomodule);
4474
0
}