Coverage Report

Created: 2026-06-21 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/frameobject.c
Line
Count
Source
1
/* Frame object implementation */
2
3
#include "Python.h"
4
#include "pycore_cell.h"          // PyCell_GetRef()
5
#include "pycore_ceval.h"         // _PyEval_SetOpcodeTrace()
6
#include "pycore_code.h"          // CO_FAST_LOCAL
7
#include "pycore_dict.h"          // _PyDict_LoadBuiltinsFromGlobals()
8
#include "pycore_frame.h"         // PyFrameObject
9
#include "pycore_function.h"      // _PyFunction_FromConstructor()
10
#include "pycore_genobject.h"     // _PyGen_GetGeneratorFromFrame()
11
#include "pycore_interpframe.h"   // _PyFrame_GetLocalsArray()
12
#include "pycore_list.h"          // _PyList_AppendTakeRef()
13
#include "pycore_modsupport.h"    // _PyArg_CheckPositional()
14
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
15
#include "pycore_opcode_metadata.h" // _PyOpcode_Caches
16
#include "pycore_optimizer.h"     // _Py_Executors_InvalidateDependency()
17
#include "pycore_tuple.h"         // _PyTuple_FromPair
18
#include "pycore_unicodeobject.h" // _PyUnicode_Equal()
19
20
#include "frameobject.h"          // PyFrameLocalsProxyObject
21
#include "opcode.h"               // EXTENDED_ARG
22
23
#include "clinic/frameobject.c.h"
24
25
26
#define PyFrameObject_CAST(op)  \
27
63.5M
    (assert(PyObject_TypeCheck((op), &PyFrame_Type)), (PyFrameObject *)(op))
28
29
#define PyFrameLocalsProxyObject_CAST(op)                           \
30
144
    (                                                               \
31
144
        assert(PyObject_TypeCheck((op), &PyFrameLocalsProxy_Type)), \
32
144
        (PyFrameLocalsProxyObject *)(op)                            \
33
144
    )
34
35
#define OFF(x) offsetof(PyFrameObject, x)
36
37
/*[clinic input]
38
class frame "PyFrameObject *" "&PyFrame_Type"
39
[clinic start generated code]*/
40
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2d1dbf2e06cf351f]*/
41
42
43
// Returns new reference or NULL
44
static PyObject *
45
framelocalsproxy_getval(_PyInterpreterFrame *frame, PyCodeObject *co, int i)
46
307
{
47
307
    _PyStackRef *fast = _PyFrame_GetLocalsArray(frame);
48
307
    _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
49
50
307
    PyObject *value = PyStackRef_AsPyObjectBorrow(fast[i]);
51
307
    PyObject *cell = NULL;
52
53
307
    if (value == NULL) {
54
123
        return NULL;
55
123
    }
56
57
184
    if (kind == CO_FAST_FREE || kind & CO_FAST_CELL) {
58
        // The cell was set when the frame was created from
59
        // the function's closure.
60
        // GH-128396: With PEP 709, it's possible to have a fast variable in
61
        // an inlined comprehension that has the same name as the cell variable
62
        // in the frame, where the `kind` obtained from frame can not guarantee
63
        // that the variable is a cell.
64
        // If the variable is not a cell, we are okay with it and we can simply
65
        // return the value.
66
0
        if (PyCell_Check(value)) {
67
0
            cell = value;
68
0
        }
69
0
    }
70
71
184
    if (cell != NULL) {
72
0
        value = PyCell_GetRef((PyCellObject *)cell);
73
0
    }
74
184
    else {
75
184
        Py_XINCREF(value);
76
184
    }
77
78
184
    if (value == NULL) {
79
0
        return NULL;
80
0
    }
81
82
184
    return value;
83
184
}
84
85
static bool
86
framelocalsproxy_hasval(_PyInterpreterFrame *frame, PyCodeObject *co, int i)
87
215
{
88
215
    PyObject *value = framelocalsproxy_getval(frame, co, i);
89
215
    if (value == NULL) {
90
123
        return false;
91
123
    }
92
92
    Py_DECREF(value);
93
92
    return true;
94
215
}
95
96
static int
97
framelocalsproxy_getkeyindex(PyFrameObject *frame, PyObject *key, bool read, PyObject **value_ptr)
98
92
{
99
    /*
100
     * Returns -2 (!) if an error occurred; exception will be set.
101
     * Returns the fast locals index of the key on success:
102
     *   - if read == true, returns the index if the value is not NULL
103
     *   - if read == false, returns the index if the value is not hidden
104
     * Otherwise returns -1.
105
     *
106
     * If read == true and value_ptr is not NULL, *value_ptr is set to
107
     * the value of the key if it is found (with a new reference).
108
     */
109
110
    // value_ptr should only be given if we are reading the value
111
92
    assert(read || value_ptr == NULL);
112
113
92
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
114
115
    // Ensure that the key is hashable.
116
92
    Py_hash_t key_hash = PyObject_Hash(key);
117
92
    if (key_hash == -1) {
118
0
        return -2;
119
0
    }
120
121
92
    bool found = false;
122
123
    // We do 2 loops here because it's highly possible the key is interned
124
    // and we can do a pointer comparison.
125
576
    for (int i = 0; i < co->co_nlocalsplus; i++) {
126
576
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
127
576
        if (name == key) {
128
92
            if (read) {
129
92
                PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
130
92
                if (value != NULL) {
131
92
                    if (value_ptr != NULL) {
132
92
                        *value_ptr = value;
133
92
                    }
134
0
                    else {
135
0
                        Py_DECREF(value);
136
0
                    }
137
92
                    return i;
138
92
                }
139
92
            } else {
140
0
                if (!(_PyLocals_GetKind(co->co_localspluskinds, i) & CO_FAST_HIDDEN)) {
141
0
                    return i;
142
0
                }
143
0
            }
144
0
            found = true;
145
0
        }
146
576
    }
147
0
    if (found) {
148
        // This is an attempt to read an unset local variable or
149
        // write to a variable that is hidden from regular write operations
150
0
        return -1;
151
0
    }
152
    // This is unlikely, but we need to make sure. This means the key
153
    // is not interned.
154
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
155
0
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
156
0
        Py_hash_t name_hash = PyObject_Hash(name);
157
0
        assert(name_hash != -1);  // keys are exact unicode
158
0
        if (name_hash != key_hash) {
159
0
            continue;
160
0
        }
161
0
        int same = PyObject_RichCompareBool(name, key, Py_EQ);
162
0
        if (same < 0) {
163
0
            return -2;
164
0
        }
165
0
        if (same) {
166
0
            if (read) {
167
0
                PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
168
0
                if (value != NULL) {
169
0
                    if (value_ptr != NULL) {
170
0
                        *value_ptr = value;
171
0
                    }
172
0
                    else {
173
0
                        Py_DECREF(value);
174
0
                    }
175
0
                    return i;
176
0
                }
177
0
            } else {
178
0
                if (!(_PyLocals_GetKind(co->co_localspluskinds, i) & CO_FAST_HIDDEN)) {
179
0
                    return i;
180
0
                }
181
0
            }
182
0
        }
183
0
    }
184
185
0
    return -1;
186
0
}
187
188
static PyObject *
189
framelocalsproxy_getitem(PyObject *self, PyObject *key)
190
92
{
191
92
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
192
92
    PyObject *value = NULL;
193
194
92
    int i = framelocalsproxy_getkeyindex(frame, key, true, &value);
195
92
    if (i == -2) {
196
0
        return NULL;
197
0
    }
198
92
    if (i >= 0) {
199
92
        assert(value != NULL);
200
92
        return value;
201
92
    }
202
92
    assert(value == NULL);
203
204
    // Okay not in the fast locals, try extra locals
205
206
0
    PyObject *extra = frame->f_extra_locals;
207
0
    if (extra != NULL) {
208
0
        if (PyDict_GetItemRef(extra, key, &value) < 0) {
209
0
            return NULL;
210
0
        }
211
0
        if (value != NULL) {
212
0
            return value;
213
0
        }
214
0
    }
215
216
0
    PyErr_Format(PyExc_KeyError, "local variable '%R' is not defined", key);
217
0
    return NULL;
218
0
}
219
220
static int
221
add_overwritten_fast_local(PyFrameObject *frame, PyObject *obj)
222
0
{
223
0
    Py_ssize_t new_size;
224
0
    if (frame->f_overwritten_fast_locals == NULL) {
225
0
        new_size = 1;
226
0
    }
227
0
    else {
228
0
        Py_ssize_t size = PyTuple_Size(frame->f_overwritten_fast_locals);
229
0
        if (size == -1) {
230
0
            return -1;
231
0
        }
232
0
        new_size = size + 1;
233
0
    }
234
0
    PyObject *new_tuple = PyTuple_New(new_size);
235
0
    if (new_tuple == NULL) {
236
0
        return -1;
237
0
    }
238
0
    for (Py_ssize_t i = 0; i < new_size - 1; i++) {
239
0
        PyObject *o = PyTuple_GET_ITEM(frame->f_overwritten_fast_locals, i);
240
0
        PyTuple_SET_ITEM(new_tuple, i, Py_NewRef(o));
241
0
    }
242
0
    PyTuple_SET_ITEM(new_tuple, new_size - 1, Py_NewRef(obj));
243
0
    Py_XSETREF(frame->f_overwritten_fast_locals, new_tuple);
244
0
    return 0;
245
0
}
246
247
static int
248
framelocalsproxy_setitem(PyObject *self, PyObject *key, PyObject *value)
249
0
{
250
    /* Merge locals into fast locals */
251
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
252
0
    _PyStackRef *fast = _PyFrame_GetLocalsArray(frame->f_frame);
253
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
254
255
0
    int i = framelocalsproxy_getkeyindex(frame, key, false, NULL);
256
0
    if (i == -2) {
257
0
        return -1;
258
0
    }
259
0
    if (i >= 0) {
260
0
        if (value == NULL) {
261
0
            PyErr_SetString(PyExc_ValueError, "cannot remove local variables from FrameLocalsProxy");
262
0
            return -1;
263
0
        }
264
265
#if _Py_TIER2
266
        _Py_Executors_InvalidateDependency(_PyInterpreterState_GET(), co, 1);
267
#endif
268
269
0
        _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
270
0
        _PyStackRef oldvalue = fast[i];
271
0
        PyObject *cell = NULL;
272
0
        if (kind == CO_FAST_FREE) {
273
            // The cell was set when the frame was created from
274
            // the function's closure.
275
0
            assert(!PyStackRef_IsNull(oldvalue) && PyCell_Check(PyStackRef_AsPyObjectBorrow(oldvalue)));
276
0
            cell = PyStackRef_AsPyObjectBorrow(oldvalue);
277
0
        } else if (kind & CO_FAST_CELL && !PyStackRef_IsNull(oldvalue)) {
278
0
            PyObject *as_obj = PyStackRef_AsPyObjectBorrow(oldvalue);
279
0
            if (PyCell_Check(as_obj)) {
280
0
                cell = as_obj;
281
0
            }
282
0
        }
283
0
        if (cell != NULL) {
284
0
            Py_XINCREF(value);
285
0
            PyCell_SetTakeRef((PyCellObject *)cell, value);
286
0
        } else if (value != PyStackRef_AsPyObjectBorrow(oldvalue)) {
287
0
            PyObject *old_obj = PyStackRef_AsPyObjectBorrow(fast[i]);
288
0
            if (old_obj != NULL && !_Py_IsImmortal(old_obj)) {
289
0
                if (add_overwritten_fast_local(frame, old_obj) < 0) {
290
0
                    return -1;
291
0
                }
292
0
                PyStackRef_CLOSE(fast[i]);
293
0
            }
294
0
            fast[i] = PyStackRef_FromPyObjectNew(value);
295
0
        }
296
0
        return 0;
297
0
    }
298
299
    // Okay not in the fast locals, try extra locals
300
301
0
    PyObject *extra = frame->f_extra_locals;
302
303
0
    if (extra == NULL) {
304
0
        if (value == NULL) {
305
0
            _PyErr_SetKeyError(key);
306
0
            return -1;
307
0
        }
308
0
        extra = PyDict_New();
309
0
        if (extra == NULL) {
310
0
            return -1;
311
0
        }
312
0
        frame->f_extra_locals = extra;
313
0
    }
314
315
0
    assert(PyDict_Check(extra));
316
317
0
    if (value == NULL) {
318
0
        return PyDict_DelItem(extra, key);
319
0
    } else {
320
0
        return PyDict_SetItem(extra, key, value);
321
0
    }
322
0
}
323
324
static int
325
framelocalsproxy_merge(PyObject* self, PyObject* other)
326
0
{
327
0
    if (!PyDict_Check(other) && !PyFrameLocalsProxy_Check(other)) {
328
0
        return -1;
329
0
    }
330
331
0
    PyObject *keys = PyMapping_Keys(other);
332
0
    if (keys == NULL) {
333
0
        return -1;
334
0
    }
335
336
0
    PyObject *iter = PyObject_GetIter(keys);
337
0
    Py_DECREF(keys);
338
0
    if (iter == NULL) {
339
0
        return -1;
340
0
    }
341
342
0
    PyObject *key = NULL;
343
0
    PyObject *value = NULL;
344
345
0
    while ((key = PyIter_Next(iter)) != NULL) {
346
0
        value = PyObject_GetItem(other, key);
347
0
        if (value == NULL) {
348
0
            Py_DECREF(key);
349
0
            Py_DECREF(iter);
350
0
            return -1;
351
0
        }
352
353
0
        if (framelocalsproxy_setitem(self, key, value) < 0) {
354
0
            Py_DECREF(key);
355
0
            Py_DECREF(value);
356
0
            Py_DECREF(iter);
357
0
            return -1;
358
0
        }
359
360
0
        Py_DECREF(key);
361
0
        Py_DECREF(value);
362
0
    }
363
364
0
    Py_DECREF(iter);
365
366
0
    if (PyErr_Occurred()) {
367
0
        return -1;
368
0
    }
369
370
0
    return 0;
371
0
}
372
373
static PyObject *
374
framelocalsproxy_keys(PyObject *self, PyObject *Py_UNUSED(ignored))
375
8
{
376
8
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
377
8
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
378
8
    PyObject *names = PyList_New(0);
379
8
    if (names == NULL) {
380
0
        return NULL;
381
0
    }
382
383
152
    for (int i = 0; i < co->co_nlocalsplus; i++) {
384
144
        if (framelocalsproxy_hasval(frame->f_frame, co, i)) {
385
92
            PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
386
92
            if (PyList_Append(names, name) < 0) {
387
0
                Py_DECREF(names);
388
0
                return NULL;
389
0
            }
390
92
        }
391
144
    }
392
393
    // Iterate through the extra locals
394
8
    if (frame->f_extra_locals) {
395
0
        assert(PyDict_Check(frame->f_extra_locals));
396
397
0
        Py_ssize_t i = 0;
398
0
        PyObject *key = NULL;
399
0
        PyObject *value = NULL;
400
401
0
        while (PyDict_Next(frame->f_extra_locals, &i, &key, &value)) {
402
0
            if (PyList_Append(names, key) < 0) {
403
0
                Py_DECREF(names);
404
0
                return NULL;
405
0
            }
406
0
        }
407
0
    }
408
409
8
    return names;
410
8
}
411
412
static void
413
framelocalsproxy_dealloc(PyObject *self)
414
44
{
415
44
    PyFrameLocalsProxyObject *proxy = PyFrameLocalsProxyObject_CAST(self);
416
44
    PyObject_GC_UnTrack(self);
417
44
    Py_CLEAR(proxy->frame);
418
44
    Py_TYPE(self)->tp_free(self);
419
44
}
420
421
static PyObject *
422
framelocalsproxy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
423
44
{
424
44
    if (PyTuple_GET_SIZE(args) != 1) {
425
0
        PyErr_Format(PyExc_TypeError,
426
0
                     "FrameLocalsProxy expected 1 argument, got %zd",
427
0
                     PyTuple_GET_SIZE(args));
428
0
        return NULL;
429
0
    }
430
44
    PyObject *item = PyTuple_GET_ITEM(args, 0);
431
432
44
    if (!PyFrame_Check(item)) {
433
0
        PyErr_Format(PyExc_TypeError, "expect frame, not %T", item);
434
0
        return NULL;
435
0
    }
436
44
    PyFrameObject *frame = (PyFrameObject*)item;
437
438
44
    if (kwds != NULL && PyDict_Size(kwds) != 0) {
439
0
        PyErr_SetString(PyExc_TypeError,
440
0
                        "FrameLocalsProxy takes no keyword arguments");
441
0
        return 0;
442
0
    }
443
444
44
    PyFrameLocalsProxyObject *self = (PyFrameLocalsProxyObject *)type->tp_alloc(type, 0);
445
44
    if (self == NULL) {
446
0
        return NULL;
447
0
    }
448
449
44
    ((PyFrameLocalsProxyObject*)self)->frame = (PyFrameObject*)Py_NewRef(frame);
450
451
44
    return (PyObject *)self;
452
44
}
453
454
static int
455
framelocalsproxy_tp_clear(PyObject *self)
456
0
{
457
0
    PyFrameLocalsProxyObject *proxy = PyFrameLocalsProxyObject_CAST(self);
458
0
    Py_CLEAR(proxy->frame);
459
0
    return 0;
460
0
}
461
462
static int
463
framelocalsproxy_visit(PyObject *self, visitproc visit, void *arg)
464
0
{
465
0
    PyFrameLocalsProxyObject *proxy = PyFrameLocalsProxyObject_CAST(self);
466
0
    Py_VISIT(proxy->frame);
467
0
    return 0;
468
0
}
469
470
static PyObject *
471
framelocalsproxy_iter(PyObject *self)
472
0
{
473
0
    PyObject* keys = framelocalsproxy_keys(self, NULL);
474
0
    if (keys == NULL) {
475
0
        return NULL;
476
0
    }
477
478
0
    PyObject* iter = PyObject_GetIter(keys);
479
0
    Py_XDECREF(keys);
480
481
0
    return iter;
482
0
}
483
484
static PyObject *
485
framelocalsproxy_richcompare(PyObject *lhs, PyObject *rhs, int op)
486
0
{
487
0
    PyFrameLocalsProxyObject *self = PyFrameLocalsProxyObject_CAST(lhs);
488
0
    if (PyFrameLocalsProxy_Check(rhs)) {
489
0
        PyFrameLocalsProxyObject *other = (PyFrameLocalsProxyObject *)rhs;
490
0
        bool result = self->frame == other->frame;
491
0
        if (op == Py_EQ) {
492
0
            return PyBool_FromLong(result);
493
0
        } else if (op == Py_NE) {
494
0
            return PyBool_FromLong(!result);
495
0
        }
496
0
    } else if (PyDict_Check(rhs)) {
497
0
        PyObject *dct = PyDict_New();
498
0
        if (dct == NULL) {
499
0
            return NULL;
500
0
        }
501
502
0
        if (PyDict_Update(dct, lhs) < 0) {
503
0
            Py_DECREF(dct);
504
0
            return NULL;
505
0
        }
506
507
0
        PyObject *result = PyObject_RichCompare(dct, rhs, op);
508
0
        Py_DECREF(dct);
509
0
        return result;
510
0
    }
511
512
0
    Py_RETURN_NOTIMPLEMENTED;
513
0
}
514
515
static PyObject *
516
framelocalsproxy_repr(PyObject *self)
517
0
{
518
0
    int i = Py_ReprEnter(self);
519
0
    if (i != 0) {
520
0
        return i > 0 ? PyUnicode_FromString("{...}") : NULL;
521
0
    }
522
523
0
    PyObject *dct = PyDict_New();
524
0
    if (dct == NULL) {
525
0
        Py_ReprLeave(self);
526
0
        return NULL;
527
0
    }
528
529
0
    if (PyDict_Update(dct, self) < 0) {
530
0
        Py_DECREF(dct);
531
0
        Py_ReprLeave(self);
532
0
        return NULL;
533
0
    }
534
535
0
    PyObject *repr = PyObject_Repr(dct);
536
0
    Py_DECREF(dct);
537
538
0
    Py_ReprLeave(self);
539
540
0
    return repr;
541
0
}
542
543
static PyObject*
544
framelocalsproxy_or(PyObject *self, PyObject *other)
545
0
{
546
0
    if (!PyDict_Check(other) && !PyFrameLocalsProxy_Check(other)) {
547
0
        Py_RETURN_NOTIMPLEMENTED;
548
0
    }
549
550
0
    PyObject *result = PyDict_New();
551
0
    if (result == NULL) {
552
0
        return NULL;
553
0
    }
554
555
0
    if (PyDict_Update(result, self) < 0) {
556
0
        Py_DECREF(result);
557
0
        return NULL;
558
0
    }
559
560
0
    if (PyDict_Update(result, other) < 0) {
561
0
        Py_DECREF(result);
562
0
        return NULL;
563
0
    }
564
565
0
    return result;
566
0
}
567
568
static PyObject*
569
framelocalsproxy_inplace_or(PyObject *self, PyObject *other)
570
0
{
571
0
    if (!PyDict_Check(other) && !PyFrameLocalsProxy_Check(other)) {
572
0
        Py_RETURN_NOTIMPLEMENTED;
573
0
    }
574
575
0
    if (framelocalsproxy_merge(self, other) < 0) {
576
0
        Py_RETURN_NOTIMPLEMENTED;
577
0
    }
578
579
0
    return Py_NewRef(self);
580
0
}
581
582
static PyObject *
583
framelocalsproxy_values(PyObject *self, PyObject *Py_UNUSED(ignored))
584
0
{
585
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
586
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
587
0
    PyObject *values = PyList_New(0);
588
0
    if (values == NULL) {
589
0
        return NULL;
590
0
    }
591
592
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
593
0
        PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
594
0
        if (value) {
595
0
            if (PyList_Append(values, value) < 0) {
596
0
                Py_DECREF(values);
597
0
                Py_DECREF(value);
598
0
                return NULL;
599
0
            }
600
0
            Py_DECREF(value);
601
0
        }
602
0
    }
603
604
    // Iterate through the extra locals
605
0
    if (frame->f_extra_locals) {
606
0
        Py_ssize_t j = 0;
607
0
        PyObject *key = NULL;
608
0
        PyObject *value = NULL;
609
0
        while (PyDict_Next(frame->f_extra_locals, &j, &key, &value)) {
610
0
            if (PyList_Append(values, value) < 0) {
611
0
                Py_DECREF(values);
612
0
                return NULL;
613
0
            }
614
0
        }
615
0
    }
616
617
0
    return values;
618
0
}
619
620
static PyObject *
621
framelocalsproxy_items(PyObject *self, PyObject *Py_UNUSED(ignored))
622
0
{
623
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
624
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
625
0
    PyObject *items = PyList_New(0);
626
0
    if (items == NULL) {
627
0
        return NULL;
628
0
    }
629
630
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
631
0
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
632
0
        PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
633
634
0
        if (value) {
635
0
            PyObject *pair = _PyTuple_FromPairSteal(Py_NewRef(name), value);
636
0
            if (pair == NULL) {
637
0
                goto error;
638
0
            }
639
640
0
            if (_PyList_AppendTakeRef((PyListObject *)items, pair) < 0) {
641
0
                goto error;
642
0
            }
643
0
        }
644
0
    }
645
646
    // Iterate through the extra locals
647
0
    if (frame->f_extra_locals) {
648
0
        Py_ssize_t j = 0;
649
0
        PyObject *key = NULL;
650
0
        PyObject *value = NULL;
651
0
        while (PyDict_Next(frame->f_extra_locals, &j, &key, &value)) {
652
0
            PyObject *pair = _PyTuple_FromPair(key, value);
653
0
            if (pair == NULL) {
654
0
                goto error;
655
0
            }
656
657
0
            if (_PyList_AppendTakeRef((PyListObject *)items, pair) < 0) {
658
0
                goto error;
659
0
            }
660
0
        }
661
0
    }
662
663
0
    return items;
664
665
0
error:
666
0
    Py_DECREF(items);
667
0
    return NULL;
668
0
}
669
670
static Py_ssize_t
671
framelocalsproxy_length(PyObject *self)
672
0
{
673
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
674
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
675
0
    Py_ssize_t size = 0;
676
677
0
    if (frame->f_extra_locals != NULL) {
678
0
        assert(PyDict_Check(frame->f_extra_locals));
679
0
        size += PyDict_Size(frame->f_extra_locals);
680
0
    }
681
682
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
683
0
        if (framelocalsproxy_hasval(frame->f_frame, co, i)) {
684
0
            size++;
685
0
        }
686
0
    }
687
0
    return size;
688
0
}
689
690
static int
691
framelocalsproxy_contains(PyObject *self, PyObject *key)
692
0
{
693
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
694
695
0
    int i = framelocalsproxy_getkeyindex(frame, key, true, NULL);
696
0
    if (i == -2) {
697
0
        return -1;
698
0
    }
699
0
    if (i >= 0) {
700
0
        return 1;
701
0
    }
702
703
0
    PyObject *extra = frame->f_extra_locals;
704
0
    if (extra != NULL) {
705
0
        return PyDict_Contains(extra, key);
706
0
    }
707
708
0
    return 0;
709
0
}
710
711
static PyObject* framelocalsproxy___contains__(PyObject *self, PyObject *key)
712
0
{
713
0
    int result = framelocalsproxy_contains(self, key);
714
0
    if (result < 0) {
715
0
        return NULL;
716
0
    }
717
0
    return PyBool_FromLong(result);
718
0
}
719
720
static PyObject*
721
framelocalsproxy_update(PyObject *self, PyObject *other)
722
0
{
723
0
    if (framelocalsproxy_merge(self, other) < 0) {
724
0
        PyErr_SetString(PyExc_TypeError, "update() argument must be dict or another FrameLocalsProxy");
725
0
        return NULL;
726
0
    }
727
728
0
    Py_RETURN_NONE;
729
0
}
730
731
static PyObject*
732
framelocalsproxy_get(PyObject* self, PyObject *const *args, Py_ssize_t nargs)
733
0
{
734
0
    if (nargs < 1 || nargs > 2) {
735
0
        PyErr_SetString(PyExc_TypeError, "get expected 1 or 2 arguments");
736
0
        return NULL;
737
0
    }
738
739
0
    PyObject *key = args[0];
740
0
    PyObject *default_value = Py_None;
741
742
0
    if (nargs == 2) {
743
0
        default_value = args[1];
744
0
    }
745
746
0
    PyObject *result = framelocalsproxy_getitem(self, key);
747
748
0
    if (result == NULL) {
749
0
        if (PyErr_ExceptionMatches(PyExc_KeyError)) {
750
0
            PyErr_Clear();
751
0
            return Py_XNewRef(default_value);
752
0
        }
753
0
        return NULL;
754
0
    }
755
756
0
    return result;
757
0
}
758
759
static PyObject*
760
framelocalsproxy_setdefault(PyObject* self, PyObject *const *args, Py_ssize_t nargs)
761
0
{
762
0
    if (nargs < 1 || nargs > 2) {
763
0
        PyErr_SetString(PyExc_TypeError, "setdefault expected 1 or 2 arguments");
764
0
        return NULL;
765
0
    }
766
767
0
    PyObject *key = args[0];
768
0
    PyObject *default_value = Py_None;
769
770
0
    if (nargs == 2) {
771
0
        default_value = args[1];
772
0
    }
773
774
0
    PyObject *result = framelocalsproxy_getitem(self, key);
775
776
0
    if (result == NULL) {
777
0
        if (PyErr_ExceptionMatches(PyExc_KeyError)) {
778
0
            PyErr_Clear();
779
0
            if (framelocalsproxy_setitem(self, key, default_value) < 0) {
780
0
                return NULL;
781
0
            }
782
0
            return Py_XNewRef(default_value);
783
0
        }
784
0
        return NULL;
785
0
    }
786
787
0
    return result;
788
0
}
789
790
static PyObject*
791
framelocalsproxy_pop(PyObject* self, PyObject *const *args, Py_ssize_t nargs)
792
0
{
793
0
    if (!_PyArg_CheckPositional("pop", nargs, 1, 2)) {
794
0
        return NULL;
795
0
    }
796
797
0
    PyObject *key = args[0];
798
0
    PyObject *default_value = NULL;
799
800
0
    if (nargs == 2) {
801
0
        default_value = args[1];
802
0
    }
803
804
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
805
806
0
    int i = framelocalsproxy_getkeyindex(frame, key, false, NULL);
807
0
    if (i == -2) {
808
0
        return NULL;
809
0
    }
810
811
0
    if (i >= 0) {
812
0
        PyErr_SetString(PyExc_ValueError, "cannot remove local variables from FrameLocalsProxy");
813
0
        return NULL;
814
0
    }
815
816
0
    PyObject *result = NULL;
817
818
0
    if (frame->f_extra_locals == NULL) {
819
0
        if (default_value != NULL) {
820
0
            return Py_XNewRef(default_value);
821
0
        } else {
822
0
            _PyErr_SetKeyError(key);
823
0
            return NULL;
824
0
        }
825
0
    }
826
827
0
    if (PyDict_Pop(frame->f_extra_locals, key, &result) < 0) {
828
0
        return NULL;
829
0
    }
830
831
0
    if (result == NULL) {
832
0
        if (default_value != NULL) {
833
0
            return Py_XNewRef(default_value);
834
0
        } else {
835
0
            _PyErr_SetKeyError(key);
836
0
            return NULL;
837
0
        }
838
0
    }
839
840
0
    return result;
841
0
}
842
843
static PyObject*
844
framelocalsproxy_copy(PyObject *self, PyObject *Py_UNUSED(ignored))
845
0
{
846
0
    PyObject* result = PyDict_New();
847
848
0
    if (result == NULL) {
849
0
        return NULL;
850
0
    }
851
852
0
    if (PyDict_Update(result, self) < 0) {
853
0
        Py_DECREF(result);
854
0
        return NULL;
855
0
    }
856
857
0
    return result;
858
0
}
859
860
static PyObject*
861
framelocalsproxy_reversed(PyObject *self, PyObject *Py_UNUSED(ignored))
862
0
{
863
0
    PyObject *result = framelocalsproxy_keys(self, NULL);
864
865
0
    if (result == NULL) {
866
0
        return NULL;
867
0
    }
868
869
0
    if (PyList_Reverse(result) < 0) {
870
0
        Py_DECREF(result);
871
0
        return NULL;
872
0
    }
873
0
    return result;
874
0
}
875
876
static PyNumberMethods framelocalsproxy_as_number = {
877
    .nb_or = framelocalsproxy_or,
878
    .nb_inplace_or = framelocalsproxy_inplace_or,
879
};
880
881
static PySequenceMethods framelocalsproxy_as_sequence = {
882
    .sq_contains = framelocalsproxy_contains,
883
};
884
885
static PyMappingMethods framelocalsproxy_as_mapping = {
886
    .mp_length = framelocalsproxy_length,
887
    .mp_subscript = framelocalsproxy_getitem,
888
    .mp_ass_subscript = framelocalsproxy_setitem,
889
};
890
891
static PyMethodDef framelocalsproxy_methods[] = {
892
    {"__contains__", framelocalsproxy___contains__, METH_O | METH_COEXIST, NULL},
893
    {"__getitem__", framelocalsproxy_getitem, METH_O | METH_COEXIST, NULL},
894
    {"update", framelocalsproxy_update, METH_O, NULL},
895
    {"__reversed__", framelocalsproxy_reversed, METH_NOARGS, NULL},
896
    {"copy", framelocalsproxy_copy, METH_NOARGS, NULL},
897
    {"keys", framelocalsproxy_keys, METH_NOARGS, NULL},
898
    {"values", framelocalsproxy_values, METH_NOARGS, NULL},
899
    {"items", _PyCFunction_CAST(framelocalsproxy_items), METH_NOARGS, NULL},
900
    {"get", _PyCFunction_CAST(framelocalsproxy_get), METH_FASTCALL, NULL},
901
    {"pop", _PyCFunction_CAST(framelocalsproxy_pop), METH_FASTCALL, NULL},
902
    {
903
        "setdefault",
904
        _PyCFunction_CAST(framelocalsproxy_setdefault),
905
        METH_FASTCALL,
906
        NULL
907
    },
908
    {NULL, NULL}   /* sentinel */
909
};
910
911
PyDoc_STRVAR(framelocalsproxy_doc,
912
"FrameLocalsProxy($frame)\n"
913
"--\n"
914
"\n"
915
"Create a write-through view of the locals dictionary for a frame.\n"
916
"\n"
917
"  frame\n"
918
"    the frame object to wrap.");
919
920
PyTypeObject PyFrameLocalsProxy_Type = {
921
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
922
    .tp_name = "FrameLocalsProxy",
923
    .tp_basicsize = sizeof(PyFrameLocalsProxyObject),
924
    .tp_dealloc = framelocalsproxy_dealloc,
925
    .tp_repr = &framelocalsproxy_repr,
926
    .tp_as_number = &framelocalsproxy_as_number,
927
    .tp_as_sequence = &framelocalsproxy_as_sequence,
928
    .tp_as_mapping = &framelocalsproxy_as_mapping,
929
    .tp_getattro = PyObject_GenericGetAttr,
930
    .tp_setattro = PyObject_GenericSetAttr,
931
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MAPPING,
932
    .tp_traverse = framelocalsproxy_visit,
933
    .tp_clear = framelocalsproxy_tp_clear,
934
    .tp_richcompare = framelocalsproxy_richcompare,
935
    .tp_iter = framelocalsproxy_iter,
936
    .tp_methods = framelocalsproxy_methods,
937
    .tp_alloc = PyType_GenericAlloc,
938
    .tp_new = framelocalsproxy_new,
939
    .tp_free = PyObject_GC_Del,
940
    .tp_doc = framelocalsproxy_doc,
941
};
942
943
PyObject *
944
_PyFrameLocalsProxy_New(PyFrameObject *frame)
945
44
{
946
44
    PyObject* args = PyTuple_Pack(1, frame);
947
44
    if (args == NULL) {
948
0
        return NULL;
949
0
    }
950
951
44
    PyObject* proxy = framelocalsproxy_new(&PyFrameLocalsProxy_Type, args, NULL);
952
44
    Py_DECREF(args);
953
44
    return proxy;
954
44
}
955
956
static PyMemberDef frame_memberlist[] = {
957
    {"f_trace_lines",   Py_T_BOOL,         OFF(f_trace_lines), 0},
958
    {NULL}      /* Sentinel */
959
};
960
961
/*[clinic input]
962
@critical_section
963
@getter
964
frame.f_locals as frame_locals
965
966
Return the mapping used by the frame to look up local variables.
967
[clinic start generated code]*/
968
969
static PyObject *
970
frame_locals_get_impl(PyFrameObject *self)
971
/*[clinic end generated code: output=b4ace8bb4cae71f4 input=7bd444d0dc8ddf44]*/
972
36
{
973
36
    assert(!_PyFrame_IsIncomplete(self->f_frame));
974
975
36
    PyCodeObject *co = _PyFrame_GetCode(self->f_frame);
976
977
36
    if (!(co->co_flags & CO_OPTIMIZED) && !_PyFrame_HasHiddenLocals(self->f_frame)) {
978
0
        if (self->f_frame->f_locals == NULL) {
979
            // We found cases when f_locals is NULL for non-optimized code.
980
            // We fill the f_locals with an empty dict to avoid crash until
981
            // we find the root cause.
982
0
            self->f_frame->f_locals = PyDict_New();
983
0
            if (self->f_frame->f_locals == NULL) {
984
0
                return NULL;
985
0
            }
986
0
        }
987
0
        return Py_NewRef(self->f_frame->f_locals);
988
0
    }
989
990
36
    return _PyFrameLocalsProxy_New(self);
991
36
}
992
993
int
994
PyFrame_GetLineNumber(PyFrameObject *f)
995
1.06M
{
996
1.06M
    assert(f != NULL);
997
1.06M
    if (f->f_lineno == -1) {
998
        // We should calculate it once. If we can't get the line number,
999
        // set f->f_lineno to 0.
1000
0
        f->f_lineno = PyUnstable_InterpreterFrame_GetLine(f->f_frame);
1001
0
        if (f->f_lineno < 0) {
1002
0
            f->f_lineno = 0;
1003
0
            return -1;
1004
0
        }
1005
0
    }
1006
1007
1.06M
    if (f->f_lineno > 0) {
1008
0
        return f->f_lineno;
1009
0
    }
1010
1.06M
    return PyUnstable_InterpreterFrame_GetLine(f->f_frame);
1011
1.06M
}
1012
1013
/*[clinic input]
1014
@critical_section
1015
@getter
1016
frame.f_lineno as frame_lineno
1017
1018
Return the current line number in the frame.
1019
[clinic start generated code]*/
1020
1021
static PyObject *
1022
frame_lineno_get_impl(PyFrameObject *self)
1023
/*[clinic end generated code: output=70f35de5ac7ad630 input=87b9ec648b742936]*/
1024
0
{
1025
0
    int lineno = PyFrame_GetLineNumber(self);
1026
0
    if (lineno < 0) {
1027
0
        Py_RETURN_NONE;
1028
0
    }
1029
0
    return PyLong_FromLong(lineno);
1030
0
}
1031
1032
/*[clinic input]
1033
@critical_section
1034
@getter
1035
frame.f_lasti as frame_lasti
1036
1037
Return the index of the last attempted instruction in the frame.
1038
[clinic start generated code]*/
1039
1040
static PyObject *
1041
frame_lasti_get_impl(PyFrameObject *self)
1042
/*[clinic end generated code: output=03275b4f0327d1a2 input=0225ed49cb1fbeeb]*/
1043
0
{
1044
0
    int lasti = PyUnstable_InterpreterFrame_GetLasti(self->f_frame);
1045
0
    if (lasti < 0) {
1046
0
        return PyLong_FromLong(-1);
1047
0
    }
1048
0
    return PyLong_FromLong(lasti);
1049
0
}
1050
1051
/*[clinic input]
1052
@critical_section
1053
@getter
1054
frame.f_globals as frame_globals
1055
1056
Return the global variables in the frame.
1057
[clinic start generated code]*/
1058
1059
static PyObject *
1060
frame_globals_get_impl(PyFrameObject *self)
1061
/*[clinic end generated code: output=7758788c32885528 input=7fff7241357d314d]*/
1062
0
{
1063
0
    PyObject *globals = self->f_frame->f_globals;
1064
0
    if (globals == NULL) {
1065
0
        globals = Py_None;
1066
0
    }
1067
0
    return Py_NewRef(globals);
1068
0
}
1069
1070
/*[clinic input]
1071
@critical_section
1072
@getter
1073
frame.f_builtins as frame_builtins
1074
1075
Return the built-in variables in the frame.
1076
[clinic start generated code]*/
1077
1078
static PyObject *
1079
frame_builtins_get_impl(PyFrameObject *self)
1080
/*[clinic end generated code: output=45362faa6d42c702 input=27c696d6ffcad2c7]*/
1081
0
{
1082
0
    PyObject *builtins = self->f_frame->f_builtins;
1083
0
    if (builtins == NULL) {
1084
0
        builtins = Py_None;
1085
0
    }
1086
0
    return Py_NewRef(builtins);
1087
0
}
1088
1089
/*[clinic input]
1090
@getter
1091
frame.f_code as frame_code
1092
1093
Return the code object being executed in this frame.
1094
[clinic start generated code]*/
1095
1096
static PyObject *
1097
frame_code_get_impl(PyFrameObject *self)
1098
/*[clinic end generated code: output=a5ed6207395a8cef input=e127e7098c124816]*/
1099
0
{
1100
0
    if (PySys_Audit("object.__getattr__", "Os", self, "f_code") < 0) {
1101
0
        return NULL;
1102
0
    }
1103
0
    return (PyObject *)PyFrame_GetCode(self);
1104
0
}
1105
1106
/*[clinic input]
1107
@critical_section
1108
@getter
1109
frame.f_back as frame_back
1110
[clinic start generated code]*/
1111
1112
static PyObject *
1113
frame_back_get_impl(PyFrameObject *self)
1114
/*[clinic end generated code: output=3a84c22a55a63c79 input=9e528570d0e1f44a]*/
1115
1.80k
{
1116
1.80k
    PyObject *res = (PyObject *)PyFrame_GetBack(self);
1117
1.80k
    if (res == NULL) {
1118
206
        Py_RETURN_NONE;
1119
206
    }
1120
1.59k
    return res;
1121
1.80k
}
1122
1123
/*[clinic input]
1124
@critical_section
1125
@getter
1126
frame.f_trace_opcodes as frame_trace_opcodes
1127
1128
Return True if opcode tracing is enabled, False otherwise.
1129
[clinic start generated code]*/
1130
1131
static PyObject *
1132
frame_trace_opcodes_get_impl(PyFrameObject *self)
1133
/*[clinic end generated code: output=53ff41d09cc32e87 input=4eb91dc88e04677a]*/
1134
0
{
1135
0
    return self->f_trace_opcodes ? Py_True : Py_False;
1136
0
}
1137
1138
/*[clinic input]
1139
@critical_section
1140
@setter
1141
frame.f_trace_opcodes as frame_trace_opcodes
1142
[clinic start generated code]*/
1143
1144
static int
1145
frame_trace_opcodes_set_impl(PyFrameObject *self, PyObject *value)
1146
/*[clinic end generated code: output=92619da2bfccd449 input=7e286eea3c0333ff]*/
1147
0
{
1148
0
    if (!PyBool_Check(value)) {
1149
0
        PyErr_SetString(PyExc_TypeError,
1150
0
                        "attribute value type must be bool");
1151
0
        return -1;
1152
0
    }
1153
0
    if (value == Py_True) {
1154
0
        self->f_trace_opcodes = 1;
1155
0
        if (self->f_trace) {
1156
0
            return _PyEval_SetOpcodeTrace(self, true);
1157
0
        }
1158
0
    }
1159
0
    else {
1160
0
        self->f_trace_opcodes = 0;
1161
0
        return _PyEval_SetOpcodeTrace(self, false);
1162
0
    }
1163
0
    return 0;
1164
0
}
1165
1166
/* Model the evaluation stack, to determine which jumps
1167
 * are safe and how many values needs to be popped.
1168
 * The stack is modelled by a 64 integer, treating any
1169
 * stack that can't fit into 64 bits as "overflowed".
1170
 */
1171
1172
typedef enum kind {
1173
    Iterator = 1,
1174
    Except = 2,
1175
    Object = 3,
1176
    Null = 4,
1177
    Lasti = 5,
1178
} Kind;
1179
1180
static int
1181
0
compatible_kind(Kind from, Kind to) {
1182
0
    if (to == 0) {
1183
0
        return 0;
1184
0
    }
1185
0
    if (to == Object) {
1186
0
        return from != Null;
1187
0
    }
1188
0
    if (to == Null) {
1189
0
        return 1;
1190
0
    }
1191
0
    return from == to;
1192
0
}
1193
1194
0
#define BITS_PER_BLOCK 3
1195
1196
0
#define UNINITIALIZED -2
1197
0
#define OVERFLOWED -1
1198
1199
0
#define MAX_STACK_ENTRIES (63/BITS_PER_BLOCK)
1200
0
#define WILL_OVERFLOW (1ULL<<((MAX_STACK_ENTRIES-1)*BITS_PER_BLOCK))
1201
1202
0
#define EMPTY_STACK 0
1203
1204
static inline int64_t
1205
push_value(int64_t stack, Kind kind)
1206
0
{
1207
0
    if (((uint64_t)stack) >= WILL_OVERFLOW) {
1208
0
        return OVERFLOWED;
1209
0
    }
1210
0
    else {
1211
0
        return (stack << BITS_PER_BLOCK) | kind;
1212
0
    }
1213
0
}
1214
1215
static inline int64_t
1216
pop_value(int64_t stack)
1217
0
{
1218
0
    return Py_ARITHMETIC_RIGHT_SHIFT(int64_t, stack, BITS_PER_BLOCK);
1219
0
}
1220
1221
0
#define MASK ((1<<BITS_PER_BLOCK)-1)
1222
1223
static inline Kind
1224
top_of_stack(int64_t stack)
1225
0
{
1226
0
    return stack & MASK;
1227
0
}
1228
1229
static inline Kind
1230
peek(int64_t stack, int n)
1231
0
{
1232
0
    assert(n >= 1);
1233
0
    return (stack>>(BITS_PER_BLOCK*(n-1))) & MASK;
1234
0
}
1235
1236
static Kind
1237
stack_swap(int64_t stack, int n)
1238
0
{
1239
0
    assert(n >= 1);
1240
0
    Kind to_swap = peek(stack, n);
1241
0
    Kind top = top_of_stack(stack);
1242
0
    int shift = BITS_PER_BLOCK*(n-1);
1243
0
    int64_t replaced_low = (stack & ~(MASK << shift)) | (top << shift);
1244
0
    int64_t replaced_top = (replaced_low & ~MASK) | to_swap;
1245
0
    return replaced_top;
1246
0
}
1247
1248
static int64_t
1249
0
pop_to_level(int64_t stack, int level) {
1250
0
    if (level == 0) {
1251
0
        return EMPTY_STACK;
1252
0
    }
1253
0
    int64_t max_item = (1<<BITS_PER_BLOCK) - 1;
1254
0
    int64_t level_max_stack = max_item << ((level-1) * BITS_PER_BLOCK);
1255
0
    while (stack > level_max_stack) {
1256
0
        stack = pop_value(stack);
1257
0
    }
1258
0
    return stack;
1259
0
}
1260
1261
#if 0
1262
/* These functions are useful for debugging the stack marking code */
1263
1264
static char
1265
tos_char(int64_t stack) {
1266
    switch(top_of_stack(stack)) {
1267
        case Iterator:
1268
            return 'I';
1269
        case Except:
1270
            return 'E';
1271
        case Object:
1272
            return 'O';
1273
        case Lasti:
1274
            return 'L';
1275
        case Null:
1276
            return 'N';
1277
    }
1278
    return '?';
1279
}
1280
1281
static void
1282
print_stack(int64_t stack) {
1283
    if (stack < 0) {
1284
        if (stack == UNINITIALIZED) {
1285
            printf("---");
1286
        }
1287
        else if (stack == OVERFLOWED) {
1288
            printf("OVERFLOWED");
1289
        }
1290
        else {
1291
            printf("??");
1292
        }
1293
        return;
1294
    }
1295
    while (stack) {
1296
        printf("%c", tos_char(stack));
1297
        stack = pop_value(stack);
1298
    }
1299
}
1300
1301
static void
1302
print_stacks(int64_t *stacks, int n) {
1303
    for (int i = 0; i < n; i++) {
1304
        printf("%d: ", i);
1305
        print_stack(stacks[i]);
1306
        printf("\n");
1307
    }
1308
}
1309
1310
#endif
1311
1312
static int64_t *
1313
mark_stacks(PyCodeObject *code_obj, int len)
1314
0
{
1315
0
    PyObject *co_code = _PyCode_GetCode(code_obj);
1316
0
    if (co_code == NULL) {
1317
0
        return NULL;
1318
0
    }
1319
0
    int64_t *stacks = PyMem_New(int64_t, len+1);
1320
1321
0
    if (stacks == NULL) {
1322
0
        PyErr_NoMemory();
1323
0
        Py_DECREF(co_code);
1324
0
        return NULL;
1325
0
    }
1326
0
    for (int i = 1; i <= len; i++) {
1327
0
        stacks[i] = UNINITIALIZED;
1328
0
    }
1329
0
    stacks[0] = EMPTY_STACK;
1330
0
    int todo = 1;
1331
0
    while (todo) {
1332
0
        todo = 0;
1333
        /* Scan instructions */
1334
0
        for (int i = 0; i < len;) {
1335
0
            int j;
1336
0
            int64_t next_stack = stacks[i];
1337
0
            _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code_obj, i);
1338
0
            int opcode = inst.op.code;
1339
0
            int oparg = 0;
1340
0
            while (opcode == EXTENDED_ARG) {
1341
0
                oparg = (oparg << 8) | inst.op.arg;
1342
0
                i++;
1343
0
                inst = _Py_GetBaseCodeUnit(code_obj, i);
1344
0
                opcode = inst.op.code;
1345
0
                stacks[i] = next_stack;
1346
0
            }
1347
0
            oparg = (oparg << 8) | inst.op.arg;
1348
0
            int next_i = i + _PyOpcode_Caches[opcode] + 1;
1349
0
            if (next_stack == UNINITIALIZED) {
1350
0
                i = next_i;
1351
0
                continue;
1352
0
            }
1353
0
            switch (opcode) {
1354
0
                case POP_JUMP_IF_FALSE:
1355
0
                case POP_JUMP_IF_TRUE:
1356
0
                case POP_JUMP_IF_NONE:
1357
0
                case POP_JUMP_IF_NOT_NONE:
1358
0
                {
1359
0
                    int64_t target_stack;
1360
0
                    j = next_i + oparg;
1361
0
                    assert(j < len);
1362
0
                    next_stack = pop_value(next_stack);
1363
0
                    target_stack = next_stack;
1364
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack);
1365
0
                    stacks[j] = target_stack;
1366
0
                    stacks[next_i] = next_stack;
1367
0
                    break;
1368
0
                }
1369
0
                case SEND:
1370
0
                    j = oparg + i + INLINE_CACHE_ENTRIES_SEND + 1;
1371
0
                    assert(j < len);
1372
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
1373
0
                    stacks[j] = next_stack;
1374
0
                    stacks[next_i] = next_stack;
1375
0
                    break;
1376
0
                case JUMP_FORWARD:
1377
0
                    j = oparg + i + 1;
1378
0
                    assert(j < len);
1379
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
1380
0
                    stacks[j] = next_stack;
1381
0
                    break;
1382
0
                case JUMP_BACKWARD:
1383
0
                case JUMP_BACKWARD_NO_INTERRUPT:
1384
0
                    j = next_i - oparg;
1385
0
                    assert(j >= 0);
1386
0
                    assert(j < len);
1387
0
                    if (stacks[j] == UNINITIALIZED && j < i) {
1388
0
                        todo = 1;
1389
0
                    }
1390
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
1391
0
                    stacks[j] = next_stack;
1392
0
                    break;
1393
0
                case GET_ITER:
1394
0
                    next_stack = push_value(pop_value(next_stack), Iterator);
1395
0
                    next_stack = push_value(next_stack, Iterator);
1396
0
                    stacks[next_i] = next_stack;
1397
0
                    break;
1398
0
                case GET_AITER:
1399
0
                    next_stack = push_value(pop_value(next_stack), Iterator);
1400
0
                    stacks[next_i] = next_stack;
1401
0
                    break;
1402
0
                case FOR_ITER:
1403
0
                {
1404
0
                    int64_t target_stack = push_value(next_stack, Object);
1405
0
                    stacks[next_i] = target_stack;
1406
0
                    j = oparg + 1 + INLINE_CACHE_ENTRIES_FOR_ITER + i;
1407
0
                    assert(j < len);
1408
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack);
1409
0
                    stacks[j] = target_stack;
1410
0
                    break;
1411
0
                }
1412
0
                case END_ASYNC_FOR:
1413
0
                    next_stack = pop_value(pop_value(next_stack));
1414
0
                    stacks[next_i] = next_stack;
1415
0
                    break;
1416
0
                case PUSH_EXC_INFO:
1417
0
                    next_stack = push_value(next_stack, Except);
1418
0
                    stacks[next_i] = next_stack;
1419
0
                    break;
1420
0
                case POP_EXCEPT:
1421
0
                    assert(top_of_stack(next_stack) == Except);
1422
0
                    next_stack = pop_value(next_stack);
1423
0
                    stacks[next_i] = next_stack;
1424
0
                    break;
1425
0
                case RETURN_VALUE:
1426
0
                    assert(pop_value(next_stack) == EMPTY_STACK);
1427
0
                    assert(top_of_stack(next_stack) == Object);
1428
0
                    break;
1429
0
                case RAISE_VARARGS:
1430
0
                    break;
1431
0
                case RERAISE:
1432
0
                    assert(top_of_stack(next_stack) == Except);
1433
                    /* End of block */
1434
0
                    break;
1435
0
                case PUSH_NULL:
1436
0
                    next_stack = push_value(next_stack, Null);
1437
0
                    stacks[next_i] = next_stack;
1438
0
                    break;
1439
0
                case LOAD_GLOBAL:
1440
0
                {
1441
0
                    int j = oparg;
1442
0
                    next_stack = push_value(next_stack, Object);
1443
0
                    if (j & 1) {
1444
0
                        next_stack = push_value(next_stack, Null);
1445
0
                    }
1446
0
                    stacks[next_i] = next_stack;
1447
0
                    break;
1448
0
                }
1449
0
                case LOAD_ATTR:
1450
0
                {
1451
0
                    assert(top_of_stack(next_stack) == Object);
1452
0
                    int j = oparg;
1453
0
                    if (j & 1) {
1454
0
                        next_stack = pop_value(next_stack);
1455
0
                        next_stack = push_value(next_stack, Object);
1456
0
                        next_stack = push_value(next_stack, Null);
1457
0
                    }
1458
0
                    stacks[next_i] = next_stack;
1459
0
                    break;
1460
0
                }
1461
0
                case SWAP:
1462
0
                {
1463
0
                    int n = oparg;
1464
0
                    next_stack = stack_swap(next_stack, n);
1465
0
                    stacks[next_i] = next_stack;
1466
0
                    break;
1467
0
                }
1468
0
                case COPY:
1469
0
                {
1470
0
                    int n = oparg;
1471
0
                    next_stack = push_value(next_stack, peek(next_stack, n));
1472
0
                    stacks[next_i] = next_stack;
1473
0
                    break;
1474
0
                }
1475
0
                case CACHE:
1476
0
                case RESERVED:
1477
0
                {
1478
0
                    assert(0);
1479
0
                }
1480
0
                default:
1481
0
                {
1482
0
                    int delta = PyCompile_OpcodeStackEffect(opcode, oparg);
1483
0
                    assert(delta != PY_INVALID_STACK_EFFECT);
1484
0
                    while (delta < 0) {
1485
0
                        next_stack = pop_value(next_stack);
1486
0
                        delta++;
1487
0
                    }
1488
0
                    while (delta > 0) {
1489
0
                        next_stack = push_value(next_stack, Object);
1490
0
                        delta--;
1491
0
                    }
1492
0
                    stacks[next_i] = next_stack;
1493
0
                }
1494
0
            }
1495
0
            i = next_i;
1496
0
        }
1497
        /* Scan exception table */
1498
0
        unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code_obj->co_exceptiontable);
1499
0
        unsigned char *end = start + PyBytes_GET_SIZE(code_obj->co_exceptiontable);
1500
0
        unsigned char *scan = start;
1501
0
        while (scan < end) {
1502
0
            int start_offset, size, handler;
1503
0
            scan = parse_varint(scan, &start_offset);
1504
0
            assert(start_offset >= 0 && start_offset < len);
1505
0
            scan = parse_varint(scan, &size);
1506
0
            assert(size >= 0 && start_offset+size <= len);
1507
0
            scan = parse_varint(scan, &handler);
1508
0
            assert(handler >= 0 && handler < len);
1509
0
            int depth_and_lasti;
1510
0
            scan = parse_varint(scan, &depth_and_lasti);
1511
0
            int level = depth_and_lasti >> 1;
1512
0
            int lasti = depth_and_lasti & 1;
1513
0
            if (stacks[start_offset] != UNINITIALIZED) {
1514
0
                if (stacks[handler] == UNINITIALIZED) {
1515
0
                    todo = 1;
1516
0
                    uint64_t target_stack = pop_to_level(stacks[start_offset], level);
1517
0
                    if (lasti) {
1518
0
                        target_stack = push_value(target_stack, Lasti);
1519
0
                    }
1520
0
                    target_stack = push_value(target_stack, Except);
1521
0
                    stacks[handler] = target_stack;
1522
0
                }
1523
0
            }
1524
0
        }
1525
0
    }
1526
0
    Py_DECREF(co_code);
1527
0
    return stacks;
1528
0
}
1529
1530
static int
1531
compatible_stack(int64_t from_stack, int64_t to_stack)
1532
0
{
1533
0
    if (from_stack < 0 || to_stack < 0) {
1534
0
        return 0;
1535
0
    }
1536
0
    while(from_stack > to_stack) {
1537
0
        from_stack = pop_value(from_stack);
1538
0
    }
1539
0
    while(from_stack) {
1540
0
        Kind from_top = top_of_stack(from_stack);
1541
0
        Kind to_top = top_of_stack(to_stack);
1542
0
        if (!compatible_kind(from_top, to_top)) {
1543
0
            return 0;
1544
0
        }
1545
0
        from_stack = pop_value(from_stack);
1546
0
        to_stack = pop_value(to_stack);
1547
0
    }
1548
0
    return to_stack == 0;
1549
0
}
1550
1551
static const char *
1552
explain_incompatible_stack(int64_t to_stack)
1553
0
{
1554
0
    assert(to_stack != 0);
1555
0
    if (to_stack == OVERFLOWED) {
1556
0
        return "stack is too deep to analyze";
1557
0
    }
1558
0
    if (to_stack == UNINITIALIZED) {
1559
0
        return "can't jump into an exception handler, or code may be unreachable";
1560
0
    }
1561
0
    Kind target_kind = top_of_stack(to_stack);
1562
0
    switch(target_kind) {
1563
0
        case Except:
1564
0
            return "can't jump into an 'except' block as there's no exception";
1565
0
        case Lasti:
1566
0
            return "can't jump into a re-raising block as there's no location";
1567
0
        case Object:
1568
0
        case Null:
1569
0
            return "incompatible stacks";
1570
0
        case Iterator:
1571
0
            return "can't jump into the body of a for loop";
1572
0
        default:
1573
0
            Py_UNREACHABLE();
1574
0
    }
1575
0
}
1576
1577
static int *
1578
marklines(PyCodeObject *code, int len)
1579
0
{
1580
0
    PyCodeAddressRange bounds;
1581
0
    _PyCode_InitAddressRange(code, &bounds);
1582
0
    assert (bounds.ar_end == 0);
1583
0
    int last_line = -1;
1584
1585
0
    int *linestarts = PyMem_New(int, len);
1586
0
    if (linestarts == NULL) {
1587
0
        return NULL;
1588
0
    }
1589
0
    for (int i = 0; i < len; i++) {
1590
0
        linestarts[i] = -1;
1591
0
    }
1592
1593
0
    while (_PyLineTable_NextAddressRange(&bounds)) {
1594
0
        assert(bounds.ar_start / (int)sizeof(_Py_CODEUNIT) < len);
1595
0
        if (bounds.ar_line != last_line && bounds.ar_line != -1) {
1596
0
            linestarts[bounds.ar_start / sizeof(_Py_CODEUNIT)] = bounds.ar_line;
1597
0
            last_line = bounds.ar_line;
1598
0
        }
1599
0
    }
1600
0
    return linestarts;
1601
0
}
1602
1603
static int
1604
first_line_not_before(int *lines, int len, int line)
1605
0
{
1606
0
    int result = INT_MAX;
1607
0
    for (int i = 0; i < len; i++) {
1608
0
        if (lines[i] < result && lines[i] >= line) {
1609
0
            result = lines[i];
1610
0
        }
1611
0
    }
1612
0
    if (result == INT_MAX) {
1613
0
        return -1;
1614
0
    }
1615
0
    return result;
1616
0
}
1617
1618
static bool frame_is_suspended(PyFrameObject *frame)
1619
0
{
1620
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
1621
0
    if (frame->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
1622
0
        PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame->f_frame);
1623
0
        return FRAME_STATE_SUSPENDED(gen->gi_frame_state);
1624
0
    }
1625
0
    return false;
1626
0
}
1627
1628
/* Setter for f_lineno - you can set f_lineno from within a trace function in
1629
 * order to jump to a given line of code, subject to some restrictions.  Most
1630
 * lines are OK to jump to because they don't make any assumptions about the
1631
 * state of the stack (obvious because you could remove the line and the code
1632
 * would still work without any stack errors), but there are some constructs
1633
 * that limit jumping:
1634
 *
1635
 *  o Any exception handlers.
1636
 *  o 'for' and 'async for' loops can't be jumped into because the
1637
 *    iterator needs to be on the stack.
1638
 *  o Jumps cannot be made from within a trace function invoked with a
1639
 *    'return' or 'exception' event since the eval loop has been exited at
1640
 *    that time.
1641
 */
1642
/*[clinic input]
1643
@critical_section
1644
@setter
1645
frame.f_lineno as frame_lineno
1646
[clinic start generated code]*/
1647
1648
static int
1649
frame_lineno_set_impl(PyFrameObject *self, PyObject *value)
1650
/*[clinic end generated code: output=e64c86ff6be64292 input=36ed3c896b27fb91]*/
1651
0
{
1652
0
    PyCodeObject *code = _PyFrame_GetCode(self->f_frame);
1653
0
    if (value == NULL) {
1654
0
        PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
1655
0
        return -1;
1656
0
    }
1657
    /* f_lineno must be an integer. */
1658
0
    if (!PyLong_CheckExact(value)) {
1659
0
        PyErr_SetString(PyExc_ValueError,
1660
0
                        "lineno must be an integer");
1661
0
        return -1;
1662
0
    }
1663
1664
0
    bool is_suspended = frame_is_suspended(self);
1665
    /*
1666
     * This code preserves the historical restrictions on
1667
     * setting the line number of a frame.
1668
     * Jumps are forbidden on a 'return' trace event (except after a yield).
1669
     * Jumps from 'call' trace events are also forbidden.
1670
     * In addition, jumps are forbidden when not tracing,
1671
     * as this is a debugging feature.
1672
     */
1673
0
    int what_event = PyThreadState_GET()->what_event;
1674
0
    if (what_event < 0) {
1675
0
        PyErr_Format(PyExc_ValueError,
1676
0
                    "f_lineno can only be set in a trace function");
1677
0
        return -1;
1678
0
    }
1679
0
    switch (what_event) {
1680
0
        case PY_MONITORING_EVENT_PY_RESUME:
1681
0
        case PY_MONITORING_EVENT_JUMP:
1682
0
        case PY_MONITORING_EVENT_BRANCH:
1683
0
        case PY_MONITORING_EVENT_BRANCH_LEFT:
1684
0
        case PY_MONITORING_EVENT_BRANCH_RIGHT:
1685
0
        case PY_MONITORING_EVENT_LINE:
1686
0
        case PY_MONITORING_EVENT_PY_YIELD:
1687
            /* Setting f_lineno is allowed for the above events */
1688
0
            break;
1689
0
        case PY_MONITORING_EVENT_PY_START:
1690
0
            PyErr_Format(PyExc_ValueError,
1691
0
                     "can't jump from the 'call' trace event of a new frame");
1692
0
            return -1;
1693
0
        case PY_MONITORING_EVENT_CALL:
1694
0
        case PY_MONITORING_EVENT_C_RETURN:
1695
0
            PyErr_SetString(PyExc_ValueError,
1696
0
                "can't jump during a call");
1697
0
            return -1;
1698
0
        case PY_MONITORING_EVENT_PY_RETURN:
1699
0
        case PY_MONITORING_EVENT_PY_UNWIND:
1700
0
        case PY_MONITORING_EVENT_PY_THROW:
1701
0
        case PY_MONITORING_EVENT_RAISE:
1702
0
        case PY_MONITORING_EVENT_C_RAISE:
1703
0
        case PY_MONITORING_EVENT_INSTRUCTION:
1704
0
        case PY_MONITORING_EVENT_EXCEPTION_HANDLED:
1705
0
            PyErr_Format(PyExc_ValueError,
1706
0
                "can only jump from a 'line' trace event");
1707
0
            return -1;
1708
0
        default:
1709
0
            PyErr_SetString(PyExc_SystemError,
1710
0
                "unexpected event type");
1711
0
            return -1;
1712
0
    }
1713
1714
0
    int new_lineno;
1715
1716
    /* Fail if the line falls outside the code block and
1717
        select first line with actual code. */
1718
0
    int overflow;
1719
0
    long l_new_lineno = PyLong_AsLongAndOverflow(value, &overflow);
1720
0
    if (overflow
1721
0
#if SIZEOF_LONG > SIZEOF_INT
1722
0
        || l_new_lineno > INT_MAX
1723
0
        || l_new_lineno < INT_MIN
1724
0
#endif
1725
0
    ) {
1726
0
        PyErr_SetString(PyExc_ValueError,
1727
0
                        "lineno out of range");
1728
0
        return -1;
1729
0
    }
1730
0
    new_lineno = (int)l_new_lineno;
1731
1732
0
    if (new_lineno < code->co_firstlineno) {
1733
0
        PyErr_Format(PyExc_ValueError,
1734
0
                    "line %d comes before the current code block",
1735
0
                    new_lineno);
1736
0
        return -1;
1737
0
    }
1738
1739
    /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
1740
     * should never overflow. */
1741
0
    int len = (int)Py_SIZE(code);
1742
0
    int *lines = marklines(code, len);
1743
0
    if (lines == NULL) {
1744
0
        return -1;
1745
0
    }
1746
1747
0
    new_lineno = first_line_not_before(lines, len, new_lineno);
1748
0
    if (new_lineno < 0) {
1749
0
        PyErr_Format(PyExc_ValueError,
1750
0
                    "line %d comes after the current code block",
1751
0
                    (int)l_new_lineno);
1752
0
        PyMem_Free(lines);
1753
0
        return -1;
1754
0
    }
1755
1756
0
    int64_t *stacks = mark_stacks(code, len);
1757
0
    if (stacks == NULL) {
1758
0
        PyMem_Free(lines);
1759
0
        return -1;
1760
0
    }
1761
1762
0
    int64_t best_stack = OVERFLOWED;
1763
0
    int best_addr = -1;
1764
0
    int64_t start_stack = stacks[_PyInterpreterFrame_LASTI(self->f_frame)];
1765
0
    int err = -1;
1766
0
    const char *msg = "cannot find bytecode for specified line";
1767
0
    for (int i = 0; i < len; i++) {
1768
0
        if (lines[i] == new_lineno) {
1769
0
            int64_t target_stack = stacks[i];
1770
0
            if (compatible_stack(start_stack, target_stack)) {
1771
0
                err = 0;
1772
0
                if (target_stack > best_stack) {
1773
0
                    best_stack = target_stack;
1774
0
                    best_addr = i;
1775
0
                }
1776
0
            }
1777
0
            else if (err < 0) {
1778
0
                if (start_stack == OVERFLOWED) {
1779
0
                    msg = "stack to deep to analyze";
1780
0
                }
1781
0
                else if (start_stack == UNINITIALIZED) {
1782
0
                    msg = "can't jump from unreachable code";
1783
0
                }
1784
0
                else {
1785
0
                    msg = explain_incompatible_stack(target_stack);
1786
0
                    err = 1;
1787
0
                }
1788
0
            }
1789
0
        }
1790
0
    }
1791
0
    PyMem_Free(stacks);
1792
0
    PyMem_Free(lines);
1793
0
    if (err) {
1794
0
        PyErr_SetString(PyExc_ValueError, msg);
1795
0
        return -1;
1796
0
    }
1797
    // Populate any NULL locals that the compiler might have "proven" to exist
1798
    // in the new location. Rather than crashing or changing co_code, just bind
1799
    // None instead:
1800
0
    int unbound = 0;
1801
0
    for (int i = 0; i < code->co_nlocalsplus; i++) {
1802
        // Counting every unbound local is overly-cautious, but a full flow
1803
        // analysis (like we do in the compiler) is probably too expensive:
1804
0
        unbound += PyStackRef_IsNull(self->f_frame->localsplus[i]);
1805
0
    }
1806
0
    if (unbound) {
1807
0
        const char *e = "assigning None to %d unbound local%s";
1808
0
        const char *s = (unbound == 1) ? "" : "s";
1809
0
        if (PyErr_WarnFormat(PyExc_RuntimeWarning, 0, e, unbound, s)) {
1810
0
            return -1;
1811
0
        }
1812
        // Do this in a second pass to avoid writing a bunch of Nones when
1813
        // warnings are being treated as errors and the previous bit raises:
1814
0
        for (int i = 0; i < code->co_nlocalsplus; i++) {
1815
0
            if (PyStackRef_IsNull(self->f_frame->localsplus[i])) {
1816
0
                self->f_frame->localsplus[i] = PyStackRef_None;
1817
0
                unbound--;
1818
0
            }
1819
0
        }
1820
0
        assert(unbound == 0);
1821
0
    }
1822
0
    if (is_suspended) {
1823
        /* Account for value popped by yield */
1824
0
        start_stack = pop_value(start_stack);
1825
0
    }
1826
0
    while (start_stack > best_stack) {
1827
0
        _PyStackRef popped = _PyFrame_StackPop(self->f_frame);
1828
0
        if (top_of_stack(start_stack) == Except) {
1829
            /* Pop exception stack as well as the evaluation stack */
1830
0
            PyObject *exc = PyStackRef_AsPyObjectBorrow(popped);
1831
0
            assert(PyExceptionInstance_Check(exc) || exc == Py_None);
1832
0
            PyThreadState *tstate = _PyThreadState_GET();
1833
0
            Py_XSETREF(tstate->exc_info->exc_value, exc == Py_None ? NULL : exc);
1834
0
        }
1835
0
        else {
1836
0
            PyStackRef_XCLOSE(popped);
1837
0
        }
1838
0
        start_stack = pop_value(start_stack);
1839
0
    }
1840
    /* Finally set the new lasti and return OK. */
1841
0
    self->f_lineno = 0;
1842
0
    self->f_frame->instr_ptr = _PyFrame_GetBytecode(self->f_frame) + best_addr;
1843
0
    return 0;
1844
0
}
1845
1846
/*[clinic input]
1847
@permit_long_summary
1848
@critical_section
1849
@getter
1850
frame.f_trace as frame_trace
1851
1852
Return the trace function for this frame, or None if no trace function is set.
1853
[clinic start generated code]*/
1854
1855
static PyObject *
1856
frame_trace_get_impl(PyFrameObject *self)
1857
/*[clinic end generated code: output=5475cbfce07826cd input=e4eacf2c68cac577]*/
1858
0
{
1859
0
    PyObject* trace = self->f_trace;
1860
0
    if (trace == NULL) {
1861
0
        trace = Py_None;
1862
0
    }
1863
0
    return Py_NewRef(trace);
1864
0
}
1865
1866
/*[clinic input]
1867
@permit_long_summary
1868
@critical_section
1869
@setter
1870
frame.f_trace as frame_trace
1871
[clinic start generated code]*/
1872
1873
static int
1874
frame_trace_set_impl(PyFrameObject *self, PyObject *value)
1875
/*[clinic end generated code: output=d6fe08335cf76ae4 input=e57380734815dac5]*/
1876
0
{
1877
0
    if (value == Py_None) {
1878
0
        value = NULL;
1879
0
    }
1880
0
    if (value != self->f_trace) {
1881
0
        Py_XSETREF(self->f_trace, Py_XNewRef(value));
1882
0
        if (value != NULL && self->f_trace_opcodes) {
1883
0
            return _PyEval_SetOpcodeTrace(self, true);
1884
0
        }
1885
0
    }
1886
0
    return 0;
1887
0
}
1888
1889
/*[clinic input]
1890
@permit_long_summary
1891
@critical_section
1892
@getter
1893
frame.f_generator as frame_generator
1894
1895
Return the generator or coroutine associated with this frame, or None.
1896
[clinic start generated code]*/
1897
1898
static PyObject *
1899
frame_generator_get_impl(PyFrameObject *self)
1900
/*[clinic end generated code: output=97aeb2392562e55b input=3ffba57ba10f84be]*/
1901
0
{
1902
0
    if (self->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
1903
0
        PyObject *gen = (PyObject *)_PyGen_GetGeneratorFromFrame(self->f_frame);
1904
0
        return Py_NewRef(gen);
1905
0
    }
1906
0
    Py_RETURN_NONE;
1907
0
}
1908
1909
1910
static PyGetSetDef frame_getsetlist[] = {
1911
    FRAME_BACK_GETSETDEF
1912
    FRAME_LOCALS_GETSETDEF
1913
    FRAME_LINENO_GETSETDEF
1914
    FRAME_TRACE_GETSETDEF
1915
    FRAME_LASTI_GETSETDEF
1916
    FRAME_GLOBALS_GETSETDEF
1917
    FRAME_BUILTINS_GETSETDEF
1918
    FRAME_CODE_GETSETDEF
1919
    FRAME_TRACE_OPCODES_GETSETDEF
1920
    FRAME_GENERATOR_GETSETDEF
1921
    {0}
1922
};
1923
1924
static void
1925
frame_dealloc(PyObject *op)
1926
63.2M
{
1927
    /* It is the responsibility of the owning generator/coroutine
1928
     * to have cleared the generator pointer */
1929
63.2M
    PyFrameObject *f = PyFrameObject_CAST(op);
1930
63.2M
    if (_PyObject_GC_IS_TRACKED(f)) {
1931
46.2M
        _PyObject_GC_UNTRACK(f);
1932
46.2M
    }
1933
1934
    /* GH-106092: If f->f_frame was on the stack and we reached the maximum
1935
     * nesting depth for deallocations, the trashcan may have delayed this
1936
     * deallocation until after f->f_frame is freed. Avoid dereferencing
1937
     * f->f_frame unless we know it still points to valid memory. */
1938
63.2M
    _PyInterpreterFrame *frame = (_PyInterpreterFrame *)f->_f_frame_data;
1939
1940
    /* Kill all local variables including specials, if we own them */
1941
63.2M
    if (f->f_frame == frame && frame->owner == FRAME_OWNED_BY_FRAME_OBJECT) {
1942
46.2M
        PyStackRef_CLEAR(frame->f_executable);
1943
46.2M
        PyStackRef_CLEAR(frame->f_funcobj);
1944
46.2M
        Py_CLEAR(frame->f_locals);
1945
46.2M
        _PyStackRef *locals = _PyFrame_GetLocalsArray(frame);
1946
46.2M
        _PyStackRef *sp = frame->stackpointer;
1947
261M
        while (sp > locals) {
1948
215M
            sp--;
1949
215M
            PyStackRef_CLEAR(*sp);
1950
215M
        }
1951
46.2M
    }
1952
63.2M
    Py_CLEAR(f->f_back);
1953
63.2M
    Py_CLEAR(f->f_trace);
1954
63.2M
    Py_CLEAR(f->f_extra_locals);
1955
63.2M
    Py_CLEAR(f->f_locals_cache);
1956
63.2M
    Py_CLEAR(f->f_overwritten_fast_locals);
1957
63.2M
    PyObject_GC_Del(f);
1958
63.2M
}
1959
1960
static int
1961
frame_traverse(PyObject *op, visitproc visit, void *arg)
1962
344k
{
1963
344k
    PyFrameObject *f = PyFrameObject_CAST(op);
1964
344k
    Py_VISIT(f->f_back);
1965
344k
    Py_VISIT(f->f_trace);
1966
344k
    Py_VISIT(f->f_extra_locals);
1967
344k
    Py_VISIT(f->f_locals_cache);
1968
344k
    Py_VISIT(f->f_overwritten_fast_locals);
1969
344k
    if (f->f_frame->owner != FRAME_OWNED_BY_FRAME_OBJECT) {
1970
0
        return 0;
1971
0
    }
1972
344k
    assert(f->f_frame->frame_obj == NULL);
1973
344k
    return _PyFrame_Traverse(f->f_frame, visit, arg);
1974
344k
}
1975
1976
static int
1977
frame_tp_clear(PyObject *op)
1978
0
{
1979
0
    PyFrameObject *f = PyFrameObject_CAST(op);
1980
0
    Py_CLEAR(f->f_trace);
1981
0
    Py_CLEAR(f->f_extra_locals);
1982
0
    Py_CLEAR(f->f_locals_cache);
1983
0
    Py_CLEAR(f->f_overwritten_fast_locals);
1984
1985
    /* locals and stack */
1986
0
    _PyStackRef *locals = _PyFrame_GetLocalsArray(f->f_frame);
1987
0
    _PyStackRef *sp = f->f_frame->stackpointer;
1988
0
    assert(sp >= locals);
1989
0
    while (sp > locals) {
1990
0
        sp--;
1991
0
        PyStackRef_CLEAR(*sp);
1992
0
    }
1993
0
    f->f_frame->stackpointer = locals;
1994
0
    Py_CLEAR(f->f_frame->f_locals);
1995
0
    return 0;
1996
0
}
1997
1998
/*[clinic input]
1999
@critical_section
2000
frame.clear
2001
2002
Clear all references held by the frame.
2003
[clinic start generated code]*/
2004
2005
static PyObject *
2006
frame_clear_impl(PyFrameObject *self)
2007
/*[clinic end generated code: output=864c662f16e9bfcc input=c358f9cff5f9b681]*/
2008
0
{
2009
0
    if (self->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
2010
0
        PyGenObject *gen = _PyGen_GetGeneratorFromFrame(self->f_frame);
2011
0
        if (_PyGen_ClearFrame(gen) < 0) {
2012
0
            return NULL;
2013
0
        }
2014
0
    }
2015
0
    else if (self->f_frame->owner == FRAME_OWNED_BY_THREAD) {
2016
0
        PyErr_SetString(PyExc_RuntimeError,
2017
0
                        "cannot clear an executing frame");
2018
0
        return NULL;
2019
0
    }
2020
0
    else {
2021
0
        assert(self->f_frame->owner == FRAME_OWNED_BY_FRAME_OBJECT);
2022
0
        (void)frame_tp_clear((PyObject *)self);
2023
0
    }
2024
0
    Py_RETURN_NONE;
2025
0
}
2026
2027
/*[clinic input]
2028
@critical_section
2029
frame.__sizeof__
2030
2031
Return the size of the frame in memory, in bytes.
2032
[clinic start generated code]*/
2033
2034
static PyObject *
2035
frame___sizeof___impl(PyFrameObject *self)
2036
/*[clinic end generated code: output=82948688e81078e2 input=908f90a83e73131d]*/
2037
0
{
2038
0
    Py_ssize_t res;
2039
0
    res = offsetof(PyFrameObject, _f_frame_data) + offsetof(_PyInterpreterFrame, localsplus);
2040
0
    PyCodeObject *code = _PyFrame_GetCode(self->f_frame);
2041
0
    res += _PyFrame_NumSlotsForCodeObject(code) * sizeof(PyObject *);
2042
0
    return PyLong_FromSsize_t(res);
2043
0
}
2044
2045
static PyObject *
2046
frame_repr(PyObject *op)
2047
0
{
2048
0
    PyFrameObject *f = PyFrameObject_CAST(op);
2049
0
    PyObject *result;
2050
0
    Py_BEGIN_CRITICAL_SECTION(f);
2051
0
    int lineno = PyFrame_GetLineNumber(f);
2052
0
    PyCodeObject *code = _PyFrame_GetCode(f->f_frame);
2053
0
    result = PyUnicode_FromFormat(
2054
0
        "<frame at %p, file %R, line %d, code %S>",
2055
0
        f, code->co_filename, lineno, code->co_name);
2056
0
    Py_END_CRITICAL_SECTION();
2057
0
    return result;
2058
0
}
2059
2060
static PyMethodDef frame_methods[] = {
2061
    FRAME_CLEAR_METHODDEF
2062
    FRAME___SIZEOF___METHODDEF
2063
    {NULL, NULL}  /* sentinel */
2064
};
2065
2066
PyTypeObject PyFrame_Type = {
2067
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2068
    "frame",
2069
    offsetof(PyFrameObject, _f_frame_data) +
2070
    offsetof(_PyInterpreterFrame, localsplus),
2071
    sizeof(PyObject *),
2072
    frame_dealloc,                              /* tp_dealloc */
2073
    0,                                          /* tp_vectorcall_offset */
2074
    0,                                          /* tp_getattr */
2075
    0,                                          /* tp_setattr */
2076
    0,                                          /* tp_as_async */
2077
    frame_repr,                                 /* tp_repr */
2078
    0,                                          /* tp_as_number */
2079
    0,                                          /* tp_as_sequence */
2080
    0,                                          /* tp_as_mapping */
2081
    0,                                          /* tp_hash */
2082
    0,                                          /* tp_call */
2083
    0,                                          /* tp_str */
2084
    PyObject_GenericGetAttr,                    /* tp_getattro */
2085
    PyObject_GenericSetAttr,                    /* tp_setattro */
2086
    0,                                          /* tp_as_buffer */
2087
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2088
    0,                                          /* tp_doc */
2089
    frame_traverse,                             /* tp_traverse */
2090
    frame_tp_clear,                             /* tp_clear */
2091
    0,                                          /* tp_richcompare */
2092
    0,                                          /* tp_weaklistoffset */
2093
    0,                                          /* tp_iter */
2094
    0,                                          /* tp_iternext */
2095
    frame_methods,                              /* tp_methods */
2096
    frame_memberlist,                           /* tp_members */
2097
    frame_getsetlist,                           /* tp_getset */
2098
    0,                                          /* tp_base */
2099
    0,                                          /* tp_dict */
2100
};
2101
2102
static void
2103
init_frame(PyThreadState *tstate, _PyInterpreterFrame *frame,
2104
           PyFunctionObject *func, PyObject *locals)
2105
304
{
2106
304
    PyCodeObject *code = (PyCodeObject *)func->func_code;
2107
304
    _PyFrame_Initialize(tstate, frame, PyStackRef_FromPyObjectNew(func),
2108
304
                        Py_XNewRef(locals), code, 0, NULL);
2109
304
}
2110
2111
PyFrameObject*
2112
_PyFrame_New_NoTrack(PyCodeObject *code)
2113
63.2M
{
2114
63.2M
    CALL_STAT_INC(frame_objects_created);
2115
63.2M
    int slots = code->co_nlocalsplus + code->co_stacksize;
2116
63.2M
    PyFrameObject *f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, slots);
2117
63.2M
    if (f == NULL) {
2118
0
        return NULL;
2119
0
    }
2120
63.2M
    f->f_back = NULL;
2121
63.2M
    f->f_trace = NULL;
2122
63.2M
    f->f_trace_lines = 1;
2123
63.2M
    f->f_trace_opcodes = 0;
2124
63.2M
    f->f_lineno = 0;
2125
63.2M
    f->f_extra_locals = NULL;
2126
63.2M
    f->f_locals_cache = NULL;
2127
63.2M
    f->f_overwritten_fast_locals = NULL;
2128
63.2M
    return f;
2129
63.2M
}
2130
2131
/* Legacy API */
2132
PyFrameObject*
2133
PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
2134
            PyObject *globals, PyObject *locals)
2135
304
{
2136
304
    PyObject *builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
2137
304
    if (builtins == NULL) {
2138
0
        return NULL;
2139
0
    }
2140
304
    PyFrameConstructor desc = {
2141
304
        .fc_globals = globals,
2142
304
        .fc_builtins = builtins,
2143
304
        .fc_name = code->co_name,
2144
304
        .fc_qualname = code->co_name,
2145
304
        .fc_code = (PyObject *)code,
2146
304
        .fc_defaults = NULL,
2147
304
        .fc_kwdefaults = NULL,
2148
304
        .fc_closure = NULL
2149
304
    };
2150
304
    PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
2151
304
    _Py_DECREF_BUILTINS(builtins);
2152
304
    if (func == NULL) {
2153
0
        return NULL;
2154
0
    }
2155
304
    PyFrameObject *f = _PyFrame_New_NoTrack(code);
2156
304
    if (f == NULL) {
2157
0
        Py_DECREF(func);
2158
0
        return NULL;
2159
0
    }
2160
304
    init_frame(tstate, (_PyInterpreterFrame *)f->_f_frame_data, func, locals);
2161
304
    f->f_frame = (_PyInterpreterFrame *)f->_f_frame_data;
2162
304
    f->f_frame->owner = FRAME_OWNED_BY_FRAME_OBJECT;
2163
    // This frame needs to be "complete", so pretend that the first RESUME ran:
2164
304
    f->f_frame->instr_ptr = _PyCode_CODE(code) + code->_co_firsttraceable + 1;
2165
304
    assert(!_PyFrame_IsIncomplete(f->f_frame));
2166
304
    Py_DECREF(func);
2167
304
    _PyObject_GC_TRACK(f);
2168
304
    return f;
2169
304
}
2170
2171
// Initialize frame free variables if needed
2172
static void
2173
frame_init_get_vars(_PyInterpreterFrame *frame)
2174
0
{
2175
    // COPY_FREE_VARS has no quickened forms, so no need to use _PyOpcode_Deopt
2176
    // here:
2177
0
    PyCodeObject *co = _PyFrame_GetCode(frame);
2178
0
    int lasti = _PyInterpreterFrame_LASTI(frame);
2179
0
    if (!(lasti < 0
2180
0
          && _PyFrame_GetBytecode(frame)->op.code == COPY_FREE_VARS
2181
0
          && PyStackRef_FunctionCheck(frame->f_funcobj)))
2182
0
    {
2183
        /* Free vars are initialized */
2184
0
        return;
2185
0
    }
2186
2187
    /* Free vars have not been initialized -- Do that */
2188
0
    PyFunctionObject *func = _PyFrame_GetFunction(frame);
2189
0
    PyObject *closure = func->func_closure;
2190
0
    int offset = PyUnstable_Code_GetFirstFree(co);
2191
0
    for (int i = 0; i < co->co_nfreevars; ++i) {
2192
0
        PyObject *o = PyTuple_GET_ITEM(closure, i);
2193
0
        frame->localsplus[offset + i] = PyStackRef_FromPyObjectNew(o);
2194
0
    }
2195
    // COPY_FREE_VARS doesn't have inline CACHEs, either:
2196
0
    frame->instr_ptr = _PyFrame_GetBytecode(frame);
2197
0
}
2198
2199
2200
static int
2201
frame_get_var(_PyInterpreterFrame *frame, PyCodeObject *co, int i,
2202
              PyObject **pvalue)
2203
0
{
2204
0
    _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
2205
2206
    /* If the namespace is unoptimized, then one of the
2207
       following cases applies:
2208
       1. It does not contain free variables, because it
2209
          uses import * or is a top-level namespace.
2210
       2. It is a class namespace.
2211
       We don't want to accidentally copy free variables
2212
       into the locals dict used by the class.
2213
    */
2214
0
    if (kind & CO_FAST_FREE && !(co->co_flags & CO_OPTIMIZED)) {
2215
0
        return 0;
2216
0
    }
2217
2218
0
    PyObject *value = NULL;
2219
0
    if (frame->stackpointer == NULL || frame->stackpointer > frame->localsplus + i) {
2220
0
        value = PyStackRef_AsPyObjectBorrow(frame->localsplus[i]);
2221
0
        if (kind & CO_FAST_FREE) {
2222
            // The cell was set by COPY_FREE_VARS.
2223
0
            assert(value != NULL && PyCell_Check(value));
2224
0
            value = PyCell_GetRef((PyCellObject *)value);
2225
0
        }
2226
0
        else if (kind & CO_FAST_CELL) {
2227
0
            if (value != NULL) {
2228
0
                if (PyCell_Check(value)) {
2229
0
                    assert(!_PyFrame_IsIncomplete(frame));
2230
0
                    value = PyCell_GetRef((PyCellObject *)value);
2231
0
                }
2232
0
                else {
2233
                    // (likely) Otherwise it is an arg (kind & CO_FAST_LOCAL),
2234
                    // with the initial value set when the frame was created...
2235
                    // (unlikely) ...or it was set via the f_locals proxy.
2236
0
                    Py_INCREF(value);
2237
0
                }
2238
0
            }
2239
0
        }
2240
0
        else {
2241
0
            Py_XINCREF(value);
2242
0
        }
2243
0
    }
2244
0
    *pvalue = value;
2245
0
    return 1;
2246
0
}
2247
2248
2249
bool
2250
_PyFrame_HasHiddenLocals(_PyInterpreterFrame *frame)
2251
384
{
2252
    /*
2253
     * This function returns if there are hidden locals introduced by PEP 709,
2254
     * which are the isolated fast locals for inline comprehensions
2255
     */
2256
384
    PyCodeObject* co = _PyFrame_GetCode(frame);
2257
2258
455
    for (int i = 0; i < co->co_nlocalsplus; i++) {
2259
71
        _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
2260
2261
71
        if (kind & CO_FAST_HIDDEN) {
2262
71
            if (framelocalsproxy_hasval(frame, co, i)) {
2263
0
                return true;
2264
0
            }
2265
71
        }
2266
71
    }
2267
2268
384
    return false;
2269
384
}
2270
2271
2272
PyObject *
2273
_PyFrame_GetLocals(_PyInterpreterFrame *frame)
2274
392
{
2275
    // We should try to avoid creating the FrameObject if possible.
2276
    // So we check if the frame is a module or class level scope
2277
392
    PyCodeObject *co = _PyFrame_GetCode(frame);
2278
2279
392
    if (!(co->co_flags & CO_OPTIMIZED) && !_PyFrame_HasHiddenLocals(frame)) {
2280
384
        if (frame->f_locals == NULL) {
2281
            // We found cases when f_locals is NULL for non-optimized code.
2282
            // We fill the f_locals with an empty dict to avoid crash until
2283
            // we find the root cause.
2284
0
            frame->f_locals = PyDict_New();
2285
0
            if (frame->f_locals == NULL) {
2286
0
                return NULL;
2287
0
            }
2288
0
        }
2289
384
        return Py_NewRef(frame->f_locals);
2290
384
    }
2291
2292
8
    PyFrameObject* f = _PyFrame_GetFrameObject(frame);
2293
8
    if (f == NULL) {
2294
0
        return NULL;
2295
0
    }
2296
2297
8
    return _PyFrameLocalsProxy_New(f);
2298
8
}
2299
2300
2301
PyObject *
2302
PyFrame_GetVar(PyFrameObject *frame_obj, PyObject *name)
2303
0
{
2304
0
    if (!PyUnicode_Check(name)) {
2305
0
        PyErr_Format(PyExc_TypeError, "name must be str, not %s",
2306
0
                     Py_TYPE(name)->tp_name);
2307
0
        return NULL;
2308
0
    }
2309
2310
0
    _PyInterpreterFrame *frame = frame_obj->f_frame;
2311
0
    frame_init_get_vars(frame);
2312
2313
0
    PyCodeObject *co = _PyFrame_GetCode(frame);
2314
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
2315
0
        PyObject *var_name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
2316
0
        if (!_PyUnicode_Equal(var_name, name)) {
2317
0
            continue;
2318
0
        }
2319
2320
0
        PyObject *value;
2321
0
        if (!frame_get_var(frame, co, i, &value)) {
2322
0
            break;
2323
0
        }
2324
0
        if (value == NULL) {
2325
0
            break;
2326
0
        }
2327
0
        return value;
2328
0
    }
2329
2330
0
    PyErr_Format(PyExc_NameError, "variable %R does not exist", name);
2331
0
    return NULL;
2332
0
}
2333
2334
2335
PyObject *
2336
PyFrame_GetVarString(PyFrameObject *frame, const char *name)
2337
0
{
2338
0
    PyObject *name_obj = PyUnicode_FromString(name);
2339
0
    if (name_obj == NULL) {
2340
0
        return NULL;
2341
0
    }
2342
0
    PyObject *value = PyFrame_GetVar(frame, name_obj);
2343
0
    Py_DECREF(name_obj);
2344
0
    return value;
2345
0
}
2346
2347
2348
int
2349
PyFrame_FastToLocalsWithError(PyFrameObject *f)
2350
0
{
2351
    // Nothing to do here, as f_locals is now a write-through proxy in
2352
    // optimized frames. Soft-deprecated, since there's no maintenance hassle.
2353
0
    return 0;
2354
0
}
2355
2356
void
2357
PyFrame_FastToLocals(PyFrameObject *f)
2358
0
{
2359
    // Nothing to do here, as f_locals is now a write-through proxy in
2360
    // optimized frames. Soft-deprecated, since there's no maintenance hassle.
2361
0
    return;
2362
0
}
2363
2364
void
2365
PyFrame_LocalsToFast(PyFrameObject *f, int clear)
2366
0
{
2367
    // Nothing to do here, as f_locals is now a write-through proxy in
2368
    // optimized frames. Soft-deprecated, since there's no maintenance hassle.
2369
0
    return;
2370
0
}
2371
2372
int
2373
_PyFrame_IsEntryFrame(PyFrameObject *frame)
2374
0
{
2375
0
    assert(frame != NULL);
2376
0
    _PyInterpreterFrame *f = frame->f_frame;
2377
0
    assert(!_PyFrame_IsIncomplete(f));
2378
0
    return f->previous && f->previous->owner == FRAME_OWNED_BY_INTERPRETER;
2379
0
}
2380
2381
PyCodeObject *
2382
PyFrame_GetCode(PyFrameObject *frame)
2383
20.7M
{
2384
20.7M
    assert(frame != NULL);
2385
20.7M
    PyObject *code;
2386
20.7M
    Py_BEGIN_CRITICAL_SECTION(frame);
2387
20.7M
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2388
20.7M
    code = Py_NewRef(_PyFrame_GetCode(frame->f_frame));
2389
20.7M
    Py_END_CRITICAL_SECTION();
2390
20.7M
    return (PyCodeObject *)code;
2391
20.7M
}
2392
2393
2394
PyFrameObject*
2395
PyFrame_GetBack(PyFrameObject *frame)
2396
19.6M
{
2397
19.6M
    assert(frame != NULL);
2398
19.6M
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2399
19.6M
    PyFrameObject *back = frame->f_back;
2400
19.6M
    if (back == NULL) {
2401
19.6M
        _PyInterpreterFrame *prev = frame->f_frame->previous;
2402
19.6M
        prev = _PyFrame_GetFirstComplete(prev);
2403
19.6M
        if (prev) {
2404
19.6M
            back = _PyFrame_GetFrameObject(prev);
2405
19.6M
        }
2406
19.6M
    }
2407
19.6M
    return (PyFrameObject*)Py_XNewRef(back);
2408
19.6M
}
2409
2410
PyObject*
2411
PyFrame_GetLocals(PyFrameObject *frame)
2412
0
{
2413
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2414
0
    return frame_locals_get((PyObject *)frame, NULL);
2415
0
}
2416
2417
PyObject*
2418
PyFrame_GetGlobals(PyFrameObject *frame)
2419
0
{
2420
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2421
0
    return frame_globals_get((PyObject *)frame, NULL);
2422
0
}
2423
2424
PyObject*
2425
PyFrame_GetBuiltins(PyFrameObject *frame)
2426
0
{
2427
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2428
0
    return frame_builtins_get((PyObject *)frame, NULL);
2429
0
}
2430
2431
int
2432
PyFrame_GetLasti(PyFrameObject *frame)
2433
0
{
2434
0
    int ret;
2435
0
    Py_BEGIN_CRITICAL_SECTION(frame);
2436
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2437
0
    int lasti = _PyInterpreterFrame_LASTI(frame->f_frame);
2438
0
    ret = lasti < 0 ? -1 : lasti * (int)sizeof(_Py_CODEUNIT);
2439
0
    Py_END_CRITICAL_SECTION();
2440
0
    return ret;
2441
0
}
2442
2443
PyObject *
2444
PyFrame_GetGenerator(PyFrameObject *frame)
2445
0
{
2446
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2447
    return frame_generator_get((PyObject *)frame, NULL);
2448
0
}