Coverage Report

Created: 2026-02-26 06:53

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