Coverage Report

Created: 2026-09-06 06:49

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